How does StringBuilder's capacity change?

前端 未结 3 540
星月不相逢
星月不相逢 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:13

    The C# standard will not specify the behavior of a BCL library class as it has nothing to do with the language specification.

    As far as I know the actual behavior is not defined in any specification and is implementation specific.

    AFAIK, The MS implementation will double the capacity once the current capacity has been reached.

    See this and this previous SO questions.


    Update:

    This has been changed in .NET 4.0. as described by Hans in his answer. Now ropes are used, adding additional 8000 characters at a time.

    MSDN, however is very careful to point out that the actual behavior is implementation specific:

    The StringBuilder dynamically allocates more space when required and increases Capacity accordingly. For performance reasons, a StringBuilder might allocate more memory than needed. The amount of memory allocated is implementation-specific.

提交回复
热议问题