You often use the Java concatenation operator (+) to concatenate (join) two strings together. And you use it with both string literals and string variables. But what’s going on behind the scenes?
String concatenation of literals
When you concatenate two string literals, the compiler creates a single string literal. That means:
String greeting = "Hello, " + "World";
becomes:
String greeting = "Hello, World";
String concatenation with variables
When you concatenate a String
reference and a literal (or another variable type), something different happens.
String louder = greeting + "!";
becomes:
String louder = (new StringBuilder()).
append(greeting).append("!").toString();
What just happened?
Here’s what actually happens:
- The compiler generates code to create a new
StringBuilder
object, using the defaultStringBuilder
constructor. The constructor only allocates space for 16char
s. - The
append()
method is called. It appends the contents of the original string to theStringBuilder
object. - The
append()
method is called again. It now appends the value on the right hand side of the+
sign. - Finally the entire
StringBuilder
is converted back to a newString
object by calling thetoString()
method.
So the following:
String s = "Joe";
s = s + " Bloggs";
actually gets converted to:
String s = "Joe";
s = new StringBuilder().append(s).
append(" Bloggs").toString();
See the problem?
This is a CPU-intensive process. Why? Because a number of temporary objects are created and then later garbage-collected. And a number of extra methods are called which internally copy characters one at a time to the new object.
The solution
You can see that it is more efficient to create a StringBuilder
with the required size. Don’t rely on the default constructor. Append everything by calling the append()
method as many times as you need. Then do a single toString()
conversion.
Of course, you don’t always need to do this. But if you have code that is frequently called and that contains a lot of string concatenation, this will definitely improve the speed.
I’m always interested in your opinion, so please leave a comment.
1 thought on “Improve the speed of string concatenation”
Great insights, I will definitely take this into consideration next time I work with strings. Thanks for the tip!.