Video in progress

Strong Middle ⚙️ JVM and memory

How does the bytecode of these two methods differ, and how is string concatenation compiled after Java 9?

String join1(List<String> parts) {
    String s = "";
    for (String p : parts) {
        s += p + ",";
    }
    return s;
}

String join2(List<String> parts) {
    StringBuilder sb = new StringBuilder();
    for (String p : parts) {
        sb.append(p).append(',');
    }
    return sb.toString();
}

In Java 9+, a + b + c turns into a single invokedynamic call (StringConcatFactory). But += inside a loop creates a new String on every iteration, so you still need a StringBuilder there.

📖 Answer

Open join1 with javap -c and you will see invokedynamic makeConcatWithConstants inside the loop. In Java 8 this would have been a new StringBuilder ... append ... toString chain. Since Java 9 (JEP 280) the compiler leaves the concatenation strategy to the runtime: the JVM calculates the needed length up front and allocates a single array. Within one expression this is faster than the old approach.

But the problem is elsewhere. s += p + "," copies the entire old string into a new one on every iteration. With 10,000 elements the total copying grows quadratically, and a lot of short-lived garbage appears. In join2, one buffer simply grows.

In an interview it is enough to say: for a + ":" + b on one line you don't need to write a StringBuilder, it only makes the code harder to read. In a loop, use StringBuilder, StringJoiner, or String.join / Collectors.joining(",").

An interesting detail: with the javac flag -XDstringConcat=inline you can get the old StringBuilder code back. It is sometimes used very early in startup to avoid the cost of the invokedynamic bootstrap (the JDK itself does this in some modules).