String concatenation and StringBuilder comparison in Java

November 27, 2016

In this post, we compare String concatenation and StringBuilder.

1. String concatenation

Strings are immutable. So we can’t change existing String, every time Java create a new String to replace previous one. String concatenation is adding two strings using operator +;

The result of executing the code above is:

2. StringBuilder

StringBuilder is a mutable sequence of characters. When you want to add new string you have to use append() method.

The result of executing the code above is:

3. Compare

String concatenation has the same bytecode as StringBuilder, but if you want to concatenate many times in loops create an instance of StringBuilder every time, and it will be slower than string builder.

loopAmount String concatenation StringBuilder
1000 11 ms 3 ms
10000 615 ms 101 ms
50000 8937 ms 2130 ms

When using StringBuilder?

You should use StringBuilder when you use

  • concatenation in loops
  • concatenation using multiple threads

Otherwise, use string concatenation to the code clarity.

Click here to add a comment

Leave a comment: