I have run a test post-JVM warmup (once the methods are compiled) and get similar results, with StringBuilder more than 30x quicker.
format: 943
stringbuilder: 26
public class TestPerf {
private static int NUM_RUN;
public static void main(String[] args) {
NUM_RUN = 100_000;
//warm up
for (int i = 0; i < 10; i++) {
method1();
method2();
}
System.gc();
System.out.println("Starting");
long sum = 0;
long start = System.nanoTime();
for (int i = 0; i < 10; i++) {
sum += method1();
}
long end = System.nanoTime();
System.out.println("format: " + (end - start) / 1000000);
System.gc();
start = System.nanoTime();
for (int i = 0; i < 10; i++) {
sum += method2();
}
end = System.nanoTime();
System.out.println("stringbuilder: " + (end - start) / 1000000);
System.out.println(sum);
}
private static int method1() {
int sum = 0;
for (int i = 0; i < NUM_RUN; i++) {
String s = String.format("test %d", i);
sum += s.length();
}
return sum;
}
private static int method2() {
int sum = 0;
for (int i = 0; i < NUM_RUN; i++) {
String s = new StringBuilder().append("test ").append(i).toString();
sum += s.length();
}
return sum;
}
}