I know that Javac compiler is able to transform String concatenation +
using StringBuilder
/StringBuffer
, and I'm curious to know starting from which version this change was introduced?
I'm using this sample code:
public class Main {
public static void main(String[] args) {
String a = args[0];
String s = "a";
s = s + a;
s = s + "b";
s = s + "c";
s = s + "d";
s = s + "e";
System.out.println(s);
}
}
So far I've tried with javac 1.8.0_121
, javac 1.6.0_20
, javac 1.5.0_22
and java 1.4.2_19
.
Here is a sample of the bytecode I see using javap -c
from 1.4.2_19
:
6: astore_2
7: new #3; //class StringBuffer
10: dup
11: invokespecial #4; //Method java/lang/StringBuffer."<init>":()V
14: aload_2
15: invokevirtual #5; //Method java/lang/StringBuffer.append:(Ljava/lang/String;)Ljava/lang/StringBuffer;
18: aload_1
19: invokevirtual #5; //Method java/lang/StringBuffer.append:(Ljava/lang/String;)Ljava/lang/StringBuffer;
22: invokevirtual #6; //Method java/lang/StringBuffer.toString:()Ljava/lang/String;
All 4 versions seems to be using the StringBuilder/StringBuffer optimization, so I'm curious to know starting from which Javac version this change was introduced?
String#+
instead ofStringBuilder
. I wanted to build a reasonably large (about 300MB) gnuplot file. There was some logic involved, and I had to build two 150MB strings in parallel, and concatenate them at the end. WithString#+
, it took half an hour and all the memory available. WithStringBuilder
, it took just a few seconds and much less memory. – Sail