Created
July 15, 2014 05:56
-
-
Save stphung/9e4b4ab9aa9e1c05064c to your computer and use it in GitHub Desktop.
String Concatenation vs. StringBuffer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output with Oracle JDK8:
100000
String concat time: 4527 ms
100000
StringBuffer append time: 3 ms