Friday, September 12, 2008
StringBuilder vs StringBuffer
byAn excellent internal Sundog blog about the differences in StringBuilder and StringBuffer by Nick Hauschild.. Good enough that I wanted to share some of it with the public audience…
[W]hy was [StringBuilder] created with the nearly the same API as another class, StringBuffer? (which has been around since the beginning of Java) Well, a history lesson shows us that there are other classes that have had the same sort of reworking. As you may recall the ArrayList class was the non-synchronized answer to the Vector class, and the HashMap class was the non-synchronized answer to the HashTable class. Well, the StringBuilder class is now the non-synchronized answer to the StringBuffer class.
The StringBuilder class is non-synchronized where the StringBuffer class is synchronized. This means that StringBuilder class is not thread-safe, and that the StringBuffer class is. The API’s are nearly the same, the only differences I have found were additional methods in the StringBuilder class.
...
Most of the applications of StringBuffer I have seen have been on single threaded applications…
Nick was right on with his assessment of StringBuffer and StringBuilder. If you are working in a multi-threaded application where you would have to worry about thread safety and synchronization, you should use StringBuffer (or Vector, or HashTable). But if you are in a single threaded application, or one in which thread management is safely handled by an external resource, then the non-synchronized version is a better choice.
However, whereas ArrayList and HashMap have both been around since java 1.2, StringBuilder is a relatively new addition to Java. That means that there is a lot of legacy code that is still using StringBuffer in single threaded applications. Is this a problem that should be addressed? Well, while this does present a performance hit, the effects of it are likely negligible. Refactoring existing code to leverage the new class would not be worth the investment. A better recommendation would be to start using StringBuilder where appropriate in all future code, and only changing out legacy code in the event of a maintenance change.