What javac does
String concatenation
StringBuilder chains up to Java 8, one invokedynamic since Java 9.
"Hello, " + name + "!" looks like the simplest expression in Java, but its bytecode changed completely in Java 9. Up to Java 8, javac built a StringBuilder, called append once for each piece, then toString. Since Java 9 (JEP 280) it emits one invokedynamic to StringConcatFactory.makeConcatWithConstants, passing only the values that vary.
The constant pieces move into a recipe string in the BootstrapMethods attribute, where \u0001 (the character U+0001) marks each argument. The JDK decides how to build the string when the call site is first linked, so the strategy can improve with each JDK release without recompiling your code.
The source
// String concatenation: StringBuilder chains before Java 9, one invokedynamic call after.
public class Concat {
static String greet(String name, int count) {
return "Hello, " + name + "! You have " + count + " new messages.";
}
static String repeat(String s, int times) {
String out = "";
for (int i = 0; i < times; i++) {
out += s;
}
return out;
}
}Compiled by javac 25 with -g and --release 8 to 25. Where releases produce different bytecode, each version is shown.
What to look for
- With
--release 8,greetallocates a builder (new,dup,invokespecial) and callsappendfive times: three constants, the name and the int. - From
--release 11on, it pushesnameandcountand makes oneinvokedynamiccall. The three constant pieces are in the recipe. - In
repeat,out += sstill builds a new String on every pass of the loop in both versions; the invokedynamic version only hides it. Use a StringBuilder yourself in loops.
Concat.class
static String greet(String name, int count)
javac --release 11 to 25
return "Hello, " + name + "! You have " + count + " new messages.";static String repeat(String s, int times)
javac --release 8
javac --release 11 to 25
String out = "";for (int i = 0; i < times; i++) {out += s;for (int i = 0; i < times; i++) {return out;The bootstrap methods
From the BootstrapMethods attribute of the --release 25 class: each invokedynamic names one of these by index.
StringConcatFactory.makeConcatWithConstants(MethodHandles$Lookup, String, MethodType, String, Object[]) : CallSite- String
"Hello, \u0001! You have \u0001 new messages."
- String
StringConcatFactory.makeConcatWithConstants(MethodHandles$Lookup, String, MethodType, String, Object[]) : CallSite- String
"\u0001\u0001"
- String