4

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?

1
  • 2
    Where is this suggested? Commented Aug 16, 2011 at 3:33

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Nothing implies in the StringBuilder source code that the capacity should be power of 2.. Yes, when grow the buffer is doubled every time but it does not mean that it won't be optimal to initialize StringBuilder with initial size of, say, 100
Actually, it grows like this int newCapacity = (value.length + 1) * 2;, so it won't stay a power of two even if you start off with one.
@Oscar Gomez +1 Even though been using StringBuilder\Buffer I never looked at the default value used when initialised and the doubling of the capacity.
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.