Tuesday, February 26, 2013

String vs StringBuilder performance trade-offs


public class StringTest {

public static void main(String[] args) {

int[] runfor = { 10, 100, 1000, 10000 };

for (int i = 0; i < runfor.length; i++) {
long start = System.currentTimeMillis();
String s = "";
for (int j = 0; j < runfor[i]; j++) {
s += "Hello" + "--" + "World!!!";
}
long end = System.currentTimeMillis();
System.out.println("String concatenation x " + runfor[i] + " times: " + (end - start) + " miliseconds");

start = System.currentTimeMillis();
StringBuilder sb = new StringBuilder();
for (int j = 0; j < runfor[i]; j++) {
sb.append("Hello");
sb.append("--");
sb.append("World!!!");
}
end = System.currentTimeMillis();
System.out.println("StringBuilder concatenation x " + runfor[i] + " times: " + (end - start) + " miliseconds");
}
}
}


Results:

String concatenation x 10 times: 0 miliseconds
StringBuilder concatenation x 10 times: 0 miliseconds
String concatenation x 100 times: 1 miliseconds
StringBuilder concatenation x 100 times: 0 miliseconds
String concatenation x 1000 times: 15 miliseconds
StringBuilder concatenation x 1000 times: 1 miliseconds
String concatenation x 10000 times: 1143 miliseconds
StringBuilder concatenation x 10000 times: 3 miliseconds

No comments:

Post a Comment