I learnt Java in 2002 and have been programming in Java from then on. Since the initial version of Java, using StringBuffer was recommended for String concatenation. Then from Java 5 (or 1.5) onwards, StringBuilder is recommended for String concatenation.

The title “We Don’t Need StringBuilder for Concatenation Anymore” caught my attention. I expected

A new library that makes string concatenation faster. An upcoming Java 9 feature.

So I opened the article.

It started with the claim that StringBuilder is no longer needed “In Java 8” That raised my curiosity.

The article starts with the drawback of using concatenation using ‘+’ operator. (It had a mistake there it said dot operator. Let us forgive that as a genuine mistake). String is immutable. And pointed out concatenating the immutable strings can become O(n²) operation.

So far so good. The author tried to appear authoritative by

adding images

source code of StringBuilder

the generated byte code (decompiled using javap).

And claimed Java compiler does some magic, and proved it with a trivial example, shown below.

Wrong Wrong and so many wrongs

Java compiler knows to use StringBuilder. So the author claims StringBuilder is not needed anymore. The author claims this is a compiler optimization from Java 8. But this has been present since 1.4 (released in 2002 from when I learnt Java) using StringBuffer. From what I know, this has been there from the first version. The author didn’t verify his own example — repeated string concatenation with 1 million strings. The compiler can optimize the million string concatenation into O(n) operation only when they are on a single statement.

Common use case for StringBuilder and the compiler cannot optimize

String concatenation in a loop. And look at the decompiled .class file (Click Files > then open the /bin/StringConcateDemo.class)

You will see that compiler internally used StringBuilder. Don’t prematurely conclude compiler optimized it. The program is still O(n²).

0: ldc #2 // String

2: astore_1

3: iconst_0

4: istore_2

5: iload_2

6: sipush 1000

9: if_icmpge 38

12: new #3 // class java/lang/StringBuilder

15: dup

16: invokespecial #4 // Method java/lang/StringBuilder.”<init>”:()V

19: aload_1

20: invokevirtual #5 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;

23: bipush 46

25: invokevirtual #6 // Method java/lang/StringBuilder.append:©Ljava/lang/StringBuilder;

28: invokevirtual #7 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;

31: astore_1

32: iinc 2, 1

35: goto 5

38: return

Look at the lines between 5–35 is the loop. You will see a new StringBuilder object is created in each iteration. That copies the string resulting in O(n²) complexity.

Run this Java program in Codiva.io Online Java Compiler to get the time taken with and without using StringBuilder. Decide for yourself.