StringBuffer/StringBuilder size in java

name_masked picture name_masked · Aug 16, 2011 · Viewed 8.7k times · Source

All,

Why is it suggested that the size of the StringBuffer/StringBuilder object should be initialized to a size of 2^{1...n}(Though usually it would be > 64). What would be the advantage/optimization would be achieved doing so?

Answer

Oscar Gomez picture Oscar Gomez · Aug 16, 2011

The suggestion is because, by default the constructor will initialize it with a size of 16, and whenever this capacity is exceeded it will double and create a new one.

Therefore if you know for sure you will be using more than 16 spaces, you should initialize it with a higher value.