How does StringBuilder's capacity change?

前端 未结 3 553
星月不相逢
星月不相逢 2020-12-06 13:42

When I have an empty StringBuilder with a capacity of 5 and I write \"hello, world!\" to it, does the C# standard specify the new capacity of the StringBu

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-06 14:09

    Depends what version of .NET you're talking about. Prior to .NET 4, StringBuilder used the standard .NET strategy, doubling the capacity of the internal buffer every time it needs to be enlarged.

    StringBuilder was completely rewritten for .NET 4, now using ropes. Extending the allocation is now done by adding another piece of rope of up to 8000 chars. Not quite as efficient as the earlier strategy but avoids trouble with big buffers clogging up the Large Object Heap. Source code is available from the Reference Source if you want to take a closer look.

提交回复
热议问题