StringBuilder Capacity

You can use a StringBuilder object without worrying about how much memory it has allocated internally for the strings that it stores.  The StringBuilder class will automatically allocate enough memory to store the strings that it is working with.
The Capacity property indicates the the maximum number of characters that can be stored in a StringBuilder object.  If an operation results in a string requiring more memory, additional memory will automatically be allocated andCapacity will be increased.
The Length property indicates the length of the string stored in the StringBuilder object.
By default, Capacity starts out at 16 and is doubled whenever more characters are required for a string.
1
2
3
4
StringBuilder sb1 = new StringBuilder();    // Len=0, Cap=16
sb1.Append("1234567890123456");             // Len=16, Cap=16
sb1.Append("z");                            // Len=17, Cap=32
sb1.Append("1234567890123456");             // Len=33, Cap=64
You can also explicitly specify capacity when you instantiate a StringBuilder:


1
StringBuilder sb2 = new StringBuilder(100);