Use StringBuilder, not StringBuffer

Java comes with two similar utilities called StringBuffer and StringBuilder. The latter was introduced in Java 5 and here is what the API doc says about it:

[StringBuilder] provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

So, in a nutshell: StringBuilder is a non-synchronized StringBuffer (and is, as a consequence, faster). When does it make sense to use a StringBuffer therefore? The only case I see is when your buffer is a field of a class used by several threads. I must admit I do not see this case.

I often see a StringBuffer created inside a method which will return a String, or passed as a parameter to a method, and my first reflex is to change it for a StringBuilder.


Did you know that when you write:

Your compiler replaces it with something like:

If you did not, well, now you know how to optimize your code regarding to String construction: append all in one time or manage the StringBuilder yourself to avoid creating and releasing many instances, which leads to poor performances.

Image courtesy from Alcibiade (CC-Attribution 4.0)