Skip to content

Instantly share code, notes, and snippets.

@tmarcus87
Last active March 29, 2016 08:56
Show Gist options
  • Save tmarcus87/6ffc46389ad6f23409d9 to your computer and use it in GitHub Desktop.
Save tmarcus87/6ffc46389ad6f23409d9 to your computer and use it in GitHub Desktop.
文字列連結パフォーマンステスト
import java.util.*;
import java.lang.*;
import java.io.*;
public class Sample
{
public static void main (String[] args) throws java.lang.Exception
{
exec("+/10times", new Runnable() {
@Override
public void run() {
String s = new String();
for (int i = 0; i < 10; i++) {
s += "hoge";
}
}
});
exec("StringBuilder/10times", new Runnable() {
@Override
public void run() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++) {
sb.append("hoge");
}
}
});
exec("StringBuffer/10times", new Runnable() {
@Override
public void run() {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 10; i++) {
sb.append("hoge");
}
}
});
}
private static void exec(String name, Runnable r) {
long s = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
r.run();
}
long e = System.currentTimeMillis();
System.out.println(s + "/" + e);
System.out.println(name + " : " + (e - s));
}
}
/*
MacBook Pro (Retina 15-inch, Mid 2015, i7 2.5GHz, 16GB RAM)
$ javac Sample.java
$ java Sample
+/10times @ 1000000sets : 214
StringBuilder/10times @ 1000000sets : 115
StringBuffer/10times @ 1000000sets : 144
+/1000times @ 10000sets : 5226
StringBuilder/1000times @ 10000sets : 76
StringBuffer/1000times @ 10000sets : 84
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment