Concatenating two strings
"Sentence number " + i
"Sentence number ".concat(String.valueOf(i))
new StringBuffer("Sentence number ").append(i).toString()
strBuffer.delete(16, 30).append(i).toString()
The graph shows four scenarios to append the String representation of an int to an existing String. The first two make use of the String class, the last two make use of the StringBuffer class. Because the StringBuffer class is mutable, it is usually faster to use it for operations on strings. Instead, the String class is immutable, which means that the + operator and the concat() method create new String instances.
The last test uses the following code inside the loop:
strBuffer.delete(16, 30).append(i).toString()
The strBuffer variable is initialized to a StringBuffer with some content. Here is where the StringBuffer class really shines: changing existing strings. This way, the existing StringBuffer instance is repeatedly used and no new instances have to be made. Of course, it depends on the situation whether repeated usage is possible.
Since Java 5, java.lang.StringBuilder is also available. It is almost the same as StringBuffer, but its methods are not synchronized. This means it is not safe to modify the StringBuilder from different threads, but it is a little bit faster. I did not include it in the comparison, because I also wanted to test Java 1.4.2, in which StringBuilder is not yet available.
The graph above shows that using a StringBuffer is indeed faster than the + operator. However, String.concat() is also suprisingly fast and can offer a shorter alternative to the StringBuffer version.
Normally, you should use the + operator because it makes the code much more readable. However, when you have determined through profiling that the String concatination is slowing your program down, a StringBuffer or StringBuilder implementation can improve the speed, especially when you use it in a smart way.