Yet again on string append vs concat vs +

Case 3 is the most performance form, but the JVM converts case 1 to case 3.

But I believe case 2 is the worst, it is not as readable as case 1 and not as perform as case 3.

If you want to concat string in a loop just use case 3, you can test the performance gain easily, but if it is not in a loop (or you are not appending lots of strings in a sequence) they are almost the same.

The cases which you shall not use the + operator are:

String a = "";
for (String x : theStrings) {
    a += x;
}

or

String a = b + c;
a = a + d;
a = a + e;
a = a + f;

As an addition to the aforementioned, there was a significant performance improvement done under JEP 280 for string concatenation only.

Pls refer to https://openjdk.java.net/jeps/280 and explanation https://dzone.com/articles/jdk-9jep-280-string-concatenations-will-never-be-t

In short, it means that from Java 9 "Hello " + "world" string concatenation is a preferred way even taking performance into account.


Case 1 is concise, expresses the intent clearly, and is equivalent to case 3.

Case 2 is less efficient, and also less readable.

Case 3 is nearly as efficient as case 1, but longer, and less readable.

Using case 3 is only better to use when you have to concatenate in a loop. Otherwise, the compiler compiles case 1 to case 3 (except it constructs the StringBuilder with new StringBuilder(a)), which makes it even more efficient than your case 3).


Case 3 is better in most aspects. In case 3, you don't endup creating 3 string objects. Because of string immutability, 2 will have overhead of creating string object for each + (or) concat.

EDIT: Re-read the document and agree with most of comments, case 1 is case3.