#71 – 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 and Capacity 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.

 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:

 StringBuilder sb2 = new StringBuilder(100);
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: