Java Five-Oh #5: StringBuilder
If you are using Java 5 you should immediately replace StringBuffer with StringBuilder. By now everyone knows that you should never use the plus sign (+) to concatenate strings. As a rule of green thumb, if I concatenate more than five strings I do so using an instance of StringBuffer. When building a dynamic string StringBuffer is faster than plain old string concatenation. But with Java 5, StringBuffer got a performance boost in the the form of StringBuilder.
StringBuilder is a drop down plug and play replacement for StringBuffer except when working in an multiple treaded environment. StringBuilder is not synchronized while StringBuffer is. It takes longer to invoke a synchronized method than a non-synchronized one so I imagine that most of the StringBuilder optimization comes from the fact that it’s methods are not synchronized. This is one of the reasons why you should use an ArrayList instead of a Vector.
Just to put up some code with this post, here is how I would write a Hello World example using StringBuilder.
public String getGreetings(String name) {
return new StringBuilder("Hello, ")
.append(name)
.toString();
}
Technorati Tags: java, java 1.5, java 5, hello world