So I've been lead to believe that using the "+" operator to append Strings on a single line was just as efficient as using a StringBuilder (and definitely much nicer on the eyes). Today though I was having some speed issues with a Logger that was appending variables and strings, it was using a "+" operator. So I made a quick test case and to my surprise found that using a StringBuilder was quicker!
The basics are I used the average of 20 runs for each number of appends, with 4 different methods(shown below).
Results, times (in milliseconds)
# of Appends 10^1 10^2 10^3 10^4 10^5 10^6 10^7 StringBuilder(capacity) 0.65 1.25 2 11.7 117.65 1213.25 11570 StringBuilder() 0.7 1.2 2.4 12.15 122 1253.7 12274.6 "+" operator 0.75 0.95 2.35 12.35 127.2 1276.5 12483.4 String.format 4.25 13.1 13.25 71.45 730.6 7217.15 -
Graph of percentage Difference from the fastest algorithm.
I've checked out the byte code, it's different for each string comparison method.
Here is what I'm using for the methods, and you can see the whole test class here.
public static String stringSpeed1(float a, float b, float c, float x, float y, float z){
StringBuilder sb = new StringBuilder(72).append("[").append(a).append(",").append(b).append(",").append(c).append("][").
append(x).append(",").append(y).append(",").append(z).append("]");
return sb.toString();
}
public static String stringSpeed2(float a, float b, float c, float x, float y, float z){
StringBuilder sb = new StringBuilder().append("[").append(a).append(",").append(b).append(",").append(c).append("][").
append(x).append(",").append(y).append(",").append(z).append("]");
return sb.toString();
}
public static String stringSpeed3(float a, float b, float c, float x, float y, float z){
return "["+a+","+b+","+c+"]["+x+","+y+","+z+"]";
}
public static String stringSpeed4(float a, float b, float c, float x, float y, float z){
return String.format("[%f,%f,%f][%f,%f,%f]", a,b,c,x,y,z);
}
I've now tried with floats, ints, and strings. All of which show more or less the same time difference.
Questions
- The "+" operator is clearly not becoming the same byte code, and the time is very different from the optimal. So what gives?
- The behavior of the algorithms betwen 100 and 10000 number of appends is very odd to me, so does anyone have an explanation?