Size of StringBuffer / StringBuilder in java

Everything,

Why is it supposed that the size of the StringBuffer / StringBuilder should be initialized with a size of 2 ^ {1 ... n} (although usually it would be> 64). What would be the advantage / optimization if this were done?

+4
source share
2 answers

What would be the advantage / optimization if this were done?

I do not think there is any advantage to this.

My advice is to choose an initial size that is slightly larger than the expected size ... if you have a moderately good rating. If you do not have a rating, you are unlikely to win by indicating the initial size at all.

Using an initial size, which is a significant revaluation, is not a good idea. It wastes space, and the JVM will have a null value for all those characters that you are not using at some point that are worth the CPU / memory cycles.

[It should be possible to empirically ascertain the cost of underestimating and re-evaluating sizes and comparing them 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 and how quickly it can be reset. In other words, they will be platform specific.]

+3
source

The suggestion is that, by default, the constructor initializes it with a size of 16 , and whenever this bandwidth is exceeded, it will be double and create a new one.

Therefore, if you know for sure that you will use more than 16 spaces, you must initialize it with a higher value.

+7
source

All Articles