Java comes with two similar utilities called
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
StringBufferin 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
StringBufferas 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
Did you know that when you write:
String string = "a" + "b";
string += "c";
Your compiler replaces it with something like:
String string = new StringBuilder().append(a).append(b).toString();
string = new StringBuilder(string).append(c).toString();
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.