Default capacity of StringBuilder

后端 未结 8 1311
野性不改
野性不改 2020-12-16 09:42

What is the default capacity of a StringBuilder?

And when should (or shouldn\'t) the default be used?

相关标签:
8条回答
  • 2020-12-16 10:24

    The default capacity of StringBuilder is 16 characters (I used .NET Reflector to find out).

    0 讨论(0)
  • 2020-12-16 10:24

    Default is 16, which seems to be the default capacity of any type of array or list in the .NET framework. The less number of reallocations you need on your StringBuilder, the better it is. Meanwhile, it is unnecessary to allocate much more than is needed, too.

    I usually instantiate the StringBuilder with some type of rough estimate as to the final size of the StringBuilder. For instance, this could be based on some iteration count that you will use later on to build the string, times the size needed for each item in this iteration.

    // where 96 is a rough estimate of the size needed for each item
    StringBuilder sb = new StringBuilder ( count * 96 );
    for ( int i = 0; i < count; i++ )
    {
    ...
    }
    

    When the size of a StringBuilder is too small for writing the next string, the internal char array of StringBuilder is reallocated to twice its current size.

    0 讨论(0)
提交回复
热议问题