Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StringBuffer/StringBuilder size in java

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?

like image 412
name_masked Avatar asked Dec 28 '22 15:12

name_masked


2 Answers

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.

like image 199
Oscar Gomez Avatar answered Jan 11 '23 09:01

Oscar Gomez


What would be the advantage/optimization would be achieved doing so?

I don't think there is any advantage at all in doing this.

My advice would be to pick an initial size that is just a bit larger than the expected size ... if you have a moderately good estimate. If you don't have an estimate, you won't gain much by supplying an initial size at all.

Using an initial size that is a significant over-estimate is not a good idea. It wastes space, and the JVM will have to zero all of those characters that you don't use at some point which costs CPU / memory cycles.

[It should be possible empirically figure out the cost of under- and over-estimating the sizes, and compare with the costs of using the default initial size. However, the numbers are likely to depend on how good the JIT optimizer is, and things like how fast memory can be copied versus how fast it can be zeroed. In other words, they will be platform specific.]

like image 26
Stephen C Avatar answered Jan 11 '23 09:01

Stephen C