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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.]