I am new to Java.
At first, I was testing the performance on String and StringBuilder in different cases.
However, I discovered that same code compiled by javac and eclipse performed differently.
I read about that String concatenation is actually using StringBuilder but why is that performance has so big difference in this case while String is 1.5x faster than StringBuilder.
Here is my testing code:
public class StringTest { public StringTest() { boolean flag = true; int code = 10001, type = 1; long time = System.nanoTime(); for (int i = 0; i < 10000000; ++i) { String msg = Long.toString(i * 1000000000); stringHandler(code, type, flag, msg); } System.out.println("Took " + (System.nanoTime() - time) + " ns by String"); time = System.nanoTime(); for (int i = 0; i < 10000000; ++i) { String msg = Long.toString(i * 1000000000); stringBuilderHandler(code, type, flag, msg); } System.out.println("Took " + (System.nanoTime() - time) + " ns by StringBuilder"); } public String stringBuilderHandler(int code, int type, boolean flag, String msg) { StringBuilder sb = new StringBuilder(); sb.append("{\"bool\":").append(flag).append(",") .append("\"code\":").append(code).append(",") .append("\"type\":").append(type).append(msg).append("}"); return sb.toString(); } public String stringHandler(int code, int type, boolean flag, String msg) { String str = "{\"bool\":"; str += flag; str += ","; str += "\"code\":"; str += code; str += ","; str += "\"type\":"; str += type; str += msg; str += "}"; return str; } public static void main(String[] args) { StringTest st = new StringTest(); } } Using javac 1.8:
Took 1066623964 ns by String Took 1540007855 ns by StringBuilder Using Eclipse:
Took 4282720864 ns by String Took 1709934263 ns by StringBuilder
javap -cand see what the bytecode looks like in both cases.