If you’re building a long String in Java, don’t stick String objects together using ‘+’, for example:
String str = "Hello"; str = str + world; str = str + "!";
It’s really slow when you do it a lot!
What should you do instead?
Use the append(String) method in StringBuffer (Java 1.4.2 on), or StringBuilder (Java 5 on). StringBuilder is slightly faster than StringBuffer, but is not thread safe. Both are much faster than concatenating String objects – by orders of magnitude. For example:
StringBuffer str = new StringBuffer("Hello"); str.append(world); str.append("!");
I set up a simple test rig to concatenate ints onto a String in a loop, by simple ‘+’ concatenation, then with a StringBuilder. Running a half dozen times and taking a rough average, the results are pretty conclusive – concatenating the wrong way can really slow things down.
- Over 10,000 repetitions, ‘+’ takes around 650 times as long (670 ms vs. 1ms).
- Over 20,000 reps, it takes around 1,800 times longer(3,500ms vs. 2ms).
- Over 100,000 reps takes around 41,000 times longer! (over 5 minutes vs. 8ms).
Why’s it so slow?
Strings in Java are immutable, which means that once a String is instantiated (be it by new String() or as a literal “blah”) it cannot be changed. When you concatenate one String to another, you actually create a third String which is the result of the concatenation
Not too much of an overhead, except when that concatenation is in some nested loop structure or the like and becomes a real bottleneck in your code. In that situation, you’re creating loads of objects that you’ll never use again and you’ll probably be running the Garbage Collector a lot to mop up, which makes things go even slower.
I first came across this when I got caught out building a big HTML table from database query results. When I was using String concatenation, it ran like a dog and the speed was pretty obviously dependent on the amount of concatenation going on. Read up on it, switched to StringBuilder, and the processing to put the String together went (in the worst case) from taking minutes to milliseconds. That’s the kind of performance improvement people notice.
There’s a little more to it, and if you’re interested, there’s more info and further optimisation steps here. The SCJP 5 qualification also covers this and a load of other simple gotchas in Java SE.