1

In .net 4.5 CLR team has change StringBuilder class a lot. Here is the code reference for StringBuilder class. Here we can find MaxChunkSize equal to 8000 and comment above this field:

// We want to keep chunk arrays out of large object heap (< 85K bytes ~ 40K chars) to be sure.
// Making the maximum chunk size big means less allocation code called, but also more waste
// in unused characters and slower inserts / replaces (since you do need to slide characters over
// within a buffer).  

So I still wonder, if we would work with StringBuilder appending large string, e.g. :

var sb = new StringBuilder();
sb.Append(<<Here comes the string with length larger than 80 000 symbols>>);

Would we still have ChunksArrays allocated in LargeObjectHeap?

Johnny_D
  • 4,592
  • 3
  • 33
  • 63

2 Answers2

0

My instincts say that you'd still get tagged by the LOH for the big string itself; if your string is bigger than the limit, it'll still live in the LOH, although the StringBuilder would not.

Let's test that out:

void Main()
{
    var big_ass_string = new String('a', 80001);
    var sb = new StringBuilder();
    sb.Append(big_ass_string);
    var generation_of_builder = GC.GetGeneration(sb);
    var generation_of_string = GC.GetGeneration(big_ass_string);
    Console.WriteLine("StringBuilder is in gen:{0}", generation_of_builder);
    Console.WriteLine("String is in gen:{0}", generation_of_string);
}

Output:

StringBuilder is in gen:0
String is in gen:2
JerKimball
  • 16,584
  • 3
  • 43
  • 55
-1

The answer is YES (even in .NET 4.5 or higher): each time you call sb.Append(...some string larger than 40K chars...); StringBuilder will allocate on Large Object Heap. (Hence, defeating the purpose of the "new" design of StringBuilder.) I posted more detailed info and a possible fix for it here: https://github.com/amikunov/Large-Object-Heap-Fix-For-.NET-String-Builder

AlexM
  • 1
  • 1