Still using StringBuffer? That’s sooo Java 1.4

Pop quiz: Hashtable is to HashMap as StringBuffer is to ... <fill in the blank>

Answer: StringBuilder.

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 language features and APIs.

While working on the project, I noticed most developers continued to use the StringBuffer class when StringBuilder 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 StringBuffer class. 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. An article 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.

3 thoughts on “Still using StringBuffer? That’s sooo Java 1.4

  1. If you decompile a Sun JDK5.0 class, you’ll see that the compiler is nearly always substituting string concatanations with StringBuilder appends.
    Whats funny about this, are all those books/articles going on about how important it is to never contact strings together, when if you didn’t and just recompile with a JDK compiler, your program may just as well run faster than had you explicitly optimized the code itself by using StringBuffer.

  2. Erik -
    Thanks for figuring that out. What’s funny about this (and you point this out) is that the code I didn’t change is optimized on my build automatically, but any code that I used StringBuffer on in an attempt to be efficient is *less* effective because it’s using a synchronized class.

  3. It’s never made sense to replace simple string concatenation with StringBuffers because that’s exactly what the compiler did in 1.0 to 1.4 anyway. Use the + operator, it’s more readable. However, it does help to replace *multiple* catenations, for example, for(i=0; i < 10; ++i) {s = s + “xyz”;} will compile to create a new StringBuffer/StringBuilder and String for each catenation, resulting in many intermediate memory allocations and copies.

Comments are closed.