Search code examples
c#stringmemory-managementgarbage-collectionlarge-object-heap

C# - can a string be stored in the Large Object Heap (LOH)?


Recently I was asked in the interview, if the strings in C# can come to the LOH. The interviewer mentioned that there is some optimization in GC logic that splits a single massive string into several smaller ones, so this string never reaches LOH.

I didn't find the related info in MSDN articles: https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/large-object-heap  and  https://learn.microsoft.com/en-us/archive/msdn-magazine/2008/june/clr-inside-out-large-object-heap-uncovered

So are there any implications or optimizations in CLR regarding storing strings in LOH? Is it somehow related to string interning?


Solution

  • I think the interviewer wanted to hear about String Intern Pool also as known as LargeHeapHandleTable.

    One of the mistake is to assume that interned string is located in String Intern Pool in LOH.

    In reality, an interned string has a hash, which is located in LargeHeapHandleTable, and then it references to Small Object Heap(SOH) or Large Object Heap(LOH).

    if an interned string more than 85kb the string will be located in LOH, in other cases it will be in 2 generation in SOH and would be stored until the application has finished.

    [The example of interned string] https://i.sstatic.net/fD0WR.png

    It is described in chapter 4 Pro .Net Memory Management by Kondrad Kokosa