I know that using the "+" concatenation operator for building strings is very inefficient, and that is why it is recommended to use the StringBuilder class, but I was wondering if this kind of pattern is inefficient too?
String some = a + "\t" + b + "\t" + c + "\t" + d + "\t" + e;
I guess here the compiler will optimize the assignment fine, or not?
This particular example will be inlined by the compiler:
String a = "a";
String b = "bb";
String c = "ccc";
String some = a + "\t" + b + "\t" + c;
Java 9+ will inline this using invokedynamic with makeConcatWithConstants making it efficient. As per javap -v
output:
Code:
stack=3, locals=5, args_size=1
0: ldc #2 // String a
2: astore_1
3: ldc #3 // String bb
5: astore_2
6: ldc #4 // String ccc
8: astore_3
9: aload_1
10: aload_2
11: aload_3
12: invokedynamic #5, 0 // InvokeDynamic #0:makeConcatWithConstants:(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
17: astore 4
19: return
However if the a
b
and c
are compile time constants compiler will further optimize the code:
final String a = "a";
final String b = "bb";
final String c = "ccc";
String some = a + "\t" + b + "\t" + c;
and some
will be loaded with a constant value:
Code:
stack=1, locals=5, args_size=1
0: ldc #2 // String a
2: astore_1
3: ldc #3 // String bb
5: astore_2
6: ldc #4 // String ccc
8: astore_3
9: ldc #5 // String a\tbb\tccc
11: astore 4
13: return
In other circumstances e.g. for
loop the compiler might not be able to produce optimized code so StringBuilder
might be faster.