Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default capacity of StringBuilder

What is the default capacity of a StringBuilder?

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

like image 312
Matt Lacey Avatar asked Oct 29 '08 09:10

Matt Lacey


People also ask

What is the default capacity of StringBuilder in Java?

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.

What is capacity method in StringBuilder?

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.

Is there a limit to string builder?

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.

How big can a StringBuilder be?

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).


2 Answers

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

like image 135
Alan Avatar answered Sep 17 '22 18:09

Alan


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.

like image 24
baretta Avatar answered Sep 18 '22 18:09

baretta