This got me thinking about the different ways in Java to concatenate Strings and how they would all perform against each other. These are the methods I'm going to investigate:
- Using the + operator
- Using a StringBuilder
- Using a StringBuffer
- Using String.concat()
- Using String.join (new in Java8)
I also experimented with String.format() but that is so hideously slow that I will leave it out of this post for now.
Before we go any further we should separate two use cases:
- Concatenating two Strings together as a single call, for example in a logging message. Because this is only one call you would have thought that performance is hardly an issue but the results are still interesting and shed light on the subject.
- Concatenating two Strings in a loop. Here performance is much more of an issue especially if your loops are large.
- The + operator is implemented with StringBuilder, so at least in the case of concatenating two Strings it should produce similar results to StringBuilder. What exactly is going on under the covers?
- StringBuilder should be the most efficient method, after all the class was designed for the very purpose of concatenating Strings and supersedes StringBuffer. But what is the overhead of creating the StringBuilder when compared with String.concat()?
- StringBuffer was the original class for concatenating Strings - unfortunately its methods are synchronized. There really is no need for the synchronization and it was subsequently replaced by StringBuilder which is not synchronized. The question is, does the JIT optimise away the synchronisation?
- String.concat() ought to work well for 2 strings but does it work well in a loop?
- String.join() has more functionality that StringBuilder, how does it affect performance if we instruct it to join Strings using an empty delimiter?
The first question I wanted to get out of the way was how the + operator works. I'd always understood that it used a StringBuilder under the covers but to prove this we need to examine the byte code.
The easiest way to look at byte code these days is with JITWatch which is a really excellent tool created to understand how your code is compiled by the JIT. It has a great view where you can view your source code side by side with byte code (also machine code if you want to go to that level).
Here's the byte code for a really simple method plus2() and we can see that indeed on line 6 a StringBuilder is created and appends the variables a (line 14) and b (line 18).
I thought it would be interesting to compare this against a handcrafted use of the StringBuffer so I create another method build2() with results below.
The byte code generated here is not quite as compact as the plus() method. The StringBuilder is stored into the variable cache (line 13) rather than just left on the stack. I'm not sure why this should be but the JIT might be able to do something with this, we'll have to see how the timings look. In any case it would be very surprising if the results of concatenating 2 strings with the plus operator and and the StringBuilder were significantly different.
I wrote a small JMH test to determine how the different methods performed. Let's first look at the two Strings test. See code below:
The results look like this:
|Benchmark||Score||Score Error (99.9%)||Unit|
The clear winner here is String.concat(). Not really surprising as it doesn't have to pay the performance penalty of creating a StringBuilder / StringBuffer for each call. It does though, have to create a new String each time (which will be significant later) but for the very simple case of joining two Stings it is faster.
Another point is that as we expected plus and StringBuilder are equivalent despite the extra byte code produced. StringBuffer is only marginally slower than StringBuilder which is interesting and shows that the JIT must be doing some magic to optimise away the synchronisation.
The next test creates an array of 100 Strings with 10 characters each. The benchmark compares how long it takes for the different methods to concatenate the 100 Strings together. See code below:
The results look quite different this time:
|Benchmark||Score||Score Error (99.9%)||Unit|
Here the plus method really suffers. The overhead of creating a StringBuilder every time you go round the loop is crippling. You can see this clearly in the byte code:
You can see that a new StringBuilder is created (line 30) every time the loop is executed. It is arguable that the JIT ought to spot this and be able to optimise, but it doesn't and using + becomes very slow.
Again StringBuilder and StringBuffer perform exactly the same but this time they are both faster than String.concat(). The price that String.concat() pays for creating a new String on each iteration of the loop eventually mounts up and a StringBuilder becomes more efficient.
String.join() does pretty well given all the extra functionality you can add to this method but, as expected, for pure concatenation it is not the best option.
If you are concatenating Strings in a single line of code I would use the + operator as it is the most readable and performance really doesn't matter that much for a single call. Also beware of String.concat() as you will almost certainly need to carry out a null check which is not necessary with the other methods.
When you are concatenating Strings in a loop you should use a StringBuilder. You could use a StringBuffer but I wouldn't necessarily trust the JIT in all circumstances to optimise away the synchronization as efficiently as it would in a benchmark.
All my results were achieved using JMH and they come with the usual health warning.