What is the default capacity of a StringBuilder
?
And when should (or shouldn't) the default be used?
Constructs a string builder initialized to the contents of the specified string. The initial capacity of the string builder is 16 plus the length of the string argument.
The capacity() method of StringBuilder Class is used to return the current capacity of StringBUilder object. The capacity is the amount of storage available to insert new characters. Syntax: public int capacity() Return Value: This method returns the current capacity of StringBuilder Class.
The maximum capacity for this implementation is Int32. MaxValue. However, this value is implementation-specific and might be different in other or later implementations. You can explicitly set the maximum capacity of a StringBuilder object by calling the StringBuilder(Int32, Int32) constructor.
The length is an int so it should hold up to 2GChar (4GB) assuming you have the memory. You are going to use "only" 600MB (300 million @ 2 bytes per character).
The default capacity of StringBuilder is 16 characters (I used .NET Reflector to find out).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With