Java String Concatenation
March 15, 2007
I was having a discussion with a co-worker today regarding String concatenation in Java. Somewhere along the line, I was told that the Java + operator, when applied to String, was slow when compared to using the append method of StringBuffer or StringBuilder. Tuns out this is a myth, sort of. I wrote a class to test it. This will first concatenate a String 100 times using the + operator, and then build the same string using StringBuilder's append method:
public class StringTest {
private int iterations;
public static void main(String[] args) {
StringTest test = new StringTest(100);
for(int i = 0; i < 10; i++) {
test.concat();
test.append();
}
}
public StringTest(int iterations) {
this.iterations = iterations;
}
private void concat() {
String foo = "";
long start = System.currentTimeMillis();
for(int i = 0; i < iterations; i++) {
foo += "foo";
}
System.out.println("String concat took "+(System.currentTimeMillis()-start)+" ms");
}
private void append() {
StringBuilder sb = new StringBuilder();
long start = System.currentTimeMillis();
for(int i = 0; i < iterations; i++) {
sb.append("foo");
}
System.out.println("String append took "+(System.currentTimeMillis()-start)+" ms");
}
}
The results of this test are:
String concat took 0 ms
String append took 0 ms
String concat took 0 ms
String append took 0 ms
String concat took 0 ms
String append took 0 ms
String concat took 0 ms
String append took 0 ms
String concat took 0 ms
String append took 0 ms
String concat took 0 ms
String append took 0 ms
String concat took 0 ms
String append took 0 ms
String concat took 0 ms
String append took 0 ms
String concat took 0 ms
String append took 0 ms
String concat took 0 ms
String append took 0 ms
So, when concatenating 100 strings, using the + incurs no significant overhead. But, if we run the same test concatenating 10000 String instead, these are the results:
String concat took 1812 ms
String append took 0 ms
String concat took 1766 ms
String append took 0 ms
String concat took 1766 ms
String append took 0 ms
String concat took 1812 ms
String append took 0 ms
String concat took 1750 ms
String append took 0 ms
String concat took 1828 ms
String append took 0 ms
String concat took 1750 ms
String append took 0 ms
String concat took 1750 ms
String append took 0 ms
String concat took 1782 ms
String append took 0 ms
String concat took 1750 ms
String append took 0 ms
So the Java String concatenation myth is rooted in fact, but as stated on this article on Java Practices, you should use the + operator whenever you are manually concatenating a bunch of Strings, like String foo = "foo"+x+"bar"+y+"baz"+z;, because for that few of a number of Strings, the code is cleaner using the + operator and the overhead of the operator is insignificant. But, if you are pulling data from an external source and building a large String by concatenating many smaller Strings, the StringBuilder would be better to use.