Pop quiz: Hashtable is to HashMap as StringBuffer is to ... <fill in the blank>
I recently worked on a Java project where the target environment was Java 1.5.
Although Java 1.5 has been out for almost three years,
the client was just upgrading to it to take advantage of its
While working on the project,
I noticed most developers continued to use the StringBuffer class
would have been the better choice.
In asking around,
most developers said they were unaware of StringBuilder.
In case you're using Java 1.5 or 1.6 but not yet using StringBuilder,
StringBuilder is an unsynchronized version of the tried-and-true
Most of StringBuffer's public methods are synchronized to
allow multiple threads to read and modify the string simultaneously.
But since StringBuffer is almost always used to build up a string within a method,
or to build a string over several method calls within a single-threaded environment,
the synchronized nature of StringBuffer is overkill.
in Dr. Dobb's Journal in June 2006 estimated switching
from StringBuffer to StringBuilder could speed string building by 38%.
That's why Sun added StringBuilder to the language in JDK 5.
None of StringBuilder's methods is synchronized,
so the class is not meant to be used when multiple threads need to access the string.
In multi-threaded contexts,
you will want to use StringBuffer.
But consider your own code.
How many times have you needed to share a StringBuffer between multiple threads?
You'll probably find that StringBuilder is often the better choice.