Update:

A friend of mine read this blog entry and showed me some decompiled Java where the compiler actually replaced the + operator. I played around with some Java compilation/decompilation and it seems that the compiler replaces the + operator with either StringBuilder or creating a new static String (e.g. “JavaDeus ” + 2008 would be compiled to “JavaDeus 2008″. Some examples can be found here. Jad files can be viewed with any text editor.


First, I have to say I don’t give performance tests much attention. However, at CS 101 I learned that using the +operator in Java to build Strings is evil. It is not only evil, it’s also a sign of noobism. At my current job, we use the + operator all over in the code. When I first saw it, I asked my colleagues if doing that doesn’t hurt the performance and memory consumption. They replied that some tests showed that there is no real difference to using StringBuilder for example, except that using StringBuilder is more work. I had read some articles about String performance, and I knew that the compiler does some optimizations, but I wasn’t fully convinced. So I did my own ‘professional’ tests, and the result was: it doesn’t matter. Hence, I settled the issue and forgot it. Yesterday, a friend of mine was complaining about Java and its String handling. Since I am Java enthusiast, I thought not Java is the problem, probably its your code. Then I saw it again, the + operator!

Typical, noob mistake, isn’t it? Hence, I told him about StringBuilder and about the evil + operator. I also created a small test to show him (or me off ;)) the difference. And the results were phenomenal! + operator was about 50 % slower than StringBuilder. With the new gained confidence in StringBuilder, I showed the results to one colleague. After a short review, he pointed out a mistake in my test. After correcting the mistake, the results were … mixed. Actually, the results showed no clear winner (+ operator is maybe a little bit faster). But I didn’t want to give up so fast, so I tested the memory consumption (String memory handling is different). Again, no difference. I added StringBuffer and String.format to the test. String.format is the slowest, which is not a surprise, and StringBuffer is slightly slower than StringBuilder and the + operator.

My conclusion is: it doesn’t matter. Use whatever you want, there is actually no real difference. But, I challenge you to convince me otherwise :)