How does StringBuilder's capacity change?

前端 未结 3 545
星月不相逢
星月不相逢 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条回答
  •  萌比男神i
    2020-12-06 14:24

    New StringBuilder (.NET 4.5 or higher) allocates an internal buffer m_ChunkChars requested by the capacity parameter:

    public StringBuilder(int capacity) { ... m_ChunkChars = new char[capacity]; ... }

    So, if capacity is smaller than 40K chars it goes on the Small Object Heap. However (contrary to popular belief), StringBuilder will still allocate on the Large Object Heap if, later, we call sb.Append(...some string larger than 40K chars...); A possible fix can be found here: https://github.com/amikunov/Large-Object-Heap-Fix-For-.NET-String-Builder

提交回复
热议问题