Which way of string concatenation is better in each example, and why?

Description:

Example 1

/* case 1.1 */ String a = s + s + s;
/* case 1.2 */ String a1 = new StringBuilder(s).append(s).append(s).toString();

Example 2

String b = "";
StringBuilder b1 = new StringBuilder();
for(int i = 0; i < 20; i++) {
/* case 2.1 */ b += s;/* case 2.2 */ b1.append(s);}
b1.toString();

Solution:

In the first example, the string concatenation will be the same. The Strings in Java are immutable, meaning that the naive string concatenation with + in case 1.1 will be far from optimal because for each concatenation a new string is created.

So, in that case the Java compiler does some optimization at compile time, changing the + chaining to a StringBuilder append. At the end, the compiled code would be completely the same.

In the second example, the data is more dynamic, in a for loop, so the Java compiler is not able to optimize it by changing the + to a StringBuilding.

Hence, for case 2.1 a new String is created on each +=, meaning that the StringBuilder .append case 2.2 will be much faster.

0 answers