Thursday, June 9, 2011

StringBuilder vs StringBuffer, Choose StringBuilder if possible

StringBuilder is an unsynchronized version of StringBuffer. That is, its instances are not safe for use by multiple threads. The upside is that it’ll be faster than StringBuffer in most implementations as well. Think of Vector vs. ArrayList.
Now let’s think about our most common use of StringBuffer. What is it? I bet it’s inside a method, as a local variable, to concatenate a bunch of strings, just like this:
public String buildHQLString() {
    StringBuffer sb = new StringBuffer();
    sb.append("something");
    // append a lot more things here
    return sb.toString();
}

It is safe to replace StringBuffer with StringBuilder in this very common case, because every thread has its own stack, in which local variables reside. So, next time you’re typing “StringBuffer sb = “, it’s a good time to reflect whether “StringBuilder sb = ” is more appropriate.

(In fact, I can’t think of a good reason to use StringBuffer now. Have any of you ever come across a case where you just absolutely have to use StringBuffer instead of StringBuilder? If anyone can enlighten me with a good, legit, uncontrived usage of StringBuffer in the comments, I’ll be grateful.)

But the default StringBuilder constructor, which has the initial capacity hardcoded to 16! So it results in a lot of extendCapacity() calls. So provide the reasonable value to StringBuilder(int capacity), instead of using StringBuilder no-arg constructor–BUT spend too much time on this and you’re doing the root of all evil, premature optimization.

No comments:

Post a Comment

Chitika