3 ms·
I can't remember how many times I've suggested that people use the optional pre-sizing parameter to Java's StringBuffer class constructor in code reviews. Many
by michaelcampbell 6y ago
I can't remember how many times I've suggested that people use the optional pre-sizing parameter to Java's StringBuffer class constructor in code reviews. Many times the size of the final string is known absolutely, or at least close enough to pre-allocate. IIRC, the default initial size is 16 bytes which is absurdly low.
- underdeserver 6y agoIt's a shame there's no way to globally set the default StringBuffer size. I bet if you optimize it just by dumb binary search, on your average project you could save on both runtime and memory usage.
- grandinj 6y agoThe default size is in fact optimally sized for "normal" Java applications, which frequently do very little with string buffers, or use them for small tokens or numbers. Source: mailing list discussion with one of the Sun devs.
- jrpelkonen 6y agoI completely agree on the buffer size statement, but at the same time, find it interesting that you would use StringBuffer enough to make that comment. I personally haven’t found any compelling use cases for it since Java 1.5 introduced StringBuilder. Would you like to share some ways you find StringBuffer useful?
- cogman10 6y agoYou shouldn't use StringBuffer. The reason it is slow is because it is "thread safe". 99% of the time, you don't really want that (especially in cases where you know how big the string will be at the end of everything). StringBuilder should be preferred for pretty much everything.
- hyperman1 6y agoWhile I agree with the conclusion to strongly prefer StringBuilder, in most cases the difference is zero: The JVM will prove no other thread can access the object, so it remooves the locks
- cogman10 6y agoI'm not sure if I agree about most cases. It is fairly trivial to come up with code that goes down a sad path (you just need to defeat the Escape analysis). That happens all the time. The JVM's Escape analysis isn't perfect.