Skip to content

Instantly share code, notes, and snippets.

@stphung
Created July 15, 2014 05:56
Show Gist options
  • Save stphung/9e4b4ab9aa9e1c05064c to your computer and use it in GitHub Desktop.
Save stphung/9e4b4ab9aa9e1c05064c to your computer and use it in GitHub Desktop.
String Concatenation vs. StringBuffer
public class Main {
private static final int ITERATIONS = 100000;
public static void main(String[] args) {
long stringConcatTime = time(Main::stringConcat);
System.out.println("String concat time: " + stringConcatTime + " ms");
long stringBufferAppendTime = time(Main::stringBufferAppend);
System.out.println("StringBuffer append time: " + stringBufferAppendTime + " ms");
}
private static void stringConcat() {
String s = "";
for (int i=0; i<ITERATIONS; i++) {
s += 'a';
}
System.out.println(s.length());
}
private static void stringBufferAppend() {
StringBuffer sb = new StringBuffer();
for (int i=0; i<ITERATIONS; i++) {
sb.append('a');
}
String s = sb.toString();
System.out.println(s.length());
}
private static long time(Runnable runnable) {
long start = System.currentTimeMillis();
runnable.run();
long finish = System.currentTimeMillis();
long delta = finish-start;
return delta;
}
}
@stphung
Copy link
Author

stphung commented Jul 15, 2014

Output with Oracle JDK8:

100000
String concat time: 4527 ms
100000
StringBuffer append time: 3 ms

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment