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?
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.
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.]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With