Recently we had a short discussion about the usage of StringBuilder and basic String Concatenation via +. I have always found using String Concatenation more readable (when using a small amount of arguments to concatenate) and also friendlier towards newcomers to the Java ecosystem. On the other hand users of StringBuilder argument with a superior performance compared to String Concatenation. Not being sure about the performance issue but remembering having heard the Java compiler will optimize String Concatenation by using StringBuilder anyway i wanted to see this for myself.
Let’s compile the following two snippets with javac:
We can now analyze the created bytecode with the class file disassembler javap, -c prints out the disassembled code.
javap -c StringTesting StringBuilderTesting
As you can see there is no difference between the two classes on the bytecode level. The compiler automatically used the StringBuilder internally for String concatenation. There will be no difference performance wise.
To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.
That being said, if performance is an issue you should use StringBuilder when constructing Strings inside of loops. The compiler won’t optimize this.
Nevertheless, if the coding standards for the project dictates to use StringBuilder to e.g. implement the toString() method you can automate this in eclipse by using Generate toString()... and change the code style to use StringBuilder/StringBuffer.