経緯
Java本格入門の「文字列操作を極める」の章で紹介されていた、実行速度の違いをただ実行するだけ。
StringBuilder
方法
System.currentTimeMillis()
メソッドを使って差分を取る
long start = System.currentTimeMillis();
...
...
long end = System.currentTimeMillis();
System.out.println("実行時間[ms]: " + (end - start));
+=
Main.java
public class Main {
public final static int SIZE;
public static void main(String[] args) {
String s = "";
long start = System.currentTimeMillis();
for (int i = 0; i < SIZE; i++) {
s += "a";
}
long end = System.currentTimeMillis();
System.out.println("実行時間[ms]: " + (end - start));
}
}
concat
Main.java
public class Main {
public final static int SIZE;
public static void main(String[] args) {
String s = "";
long start = System.currentTimeMillis();
for (int i = 0; i < SIZE; i++) {
s.concat("a");
}
long end = System.currentTimeMillis();
System.out.println("実行時間[ms]: " + (end - start));
}
}
StringBuider
Main.java
public class Main {
public final static int SIZE;
public static void main(String[] args) {
String s = "";
StringBuilder builder = new StringBuilder();
long start = System.currentTimeMillis();
for (int i = 0; i < SIZE; i++) {
builder.append("a");
}
long end = System.currentTimeMillis();
System.out.println("実行時間[ms]: " + (end - start));
}
}
SIZE = 10_000
+=
実行時間[ms]: 61
concat
実行時間[ms]: 2
StringBuilder
実行時間[ms]: 2
SIZE = 100_000
+=
実行時間[ms]: 1524
concat
実行時間[ms]: 9
StringBuilder
実行時間[ms]: 12
SIZE = 1_000_000
+=
実行時間[ms]: 69499
concat
実行時間[ms]: 36
StringBuilder
実行時間[ms]: 28
SIZE = 10_000_000
+=
はもうやめます
concat
実行時間[ms]: 170
StringBuilder
実行時間[ms]: 86
SIZE = 100_000_000
concat
実行時間[ms]: 867
StringBuilder
実行時間[ms]: 550
SIZE = 1_000_000_000
concat
実行時間[ms]: 5903
StringBuilder
実行時間[ms]: 5352
StringBuffer
StringBuilder
とメソッドは全て同じで、スレッドセーフ(マルチスレッドでも問題なく動作する)があるかどうか。
結論
- 結局バッファリングする
StringBuilder
が一番早い - ちょっとした文字列連結は
+=
でいい。
Every string builder has a capacity. As long as the length of the character sequence contained in the string builder does not exceed the capacity, it is not necessary to allocate a new internal buffer. If the internal buffer overflows, it is automatically made larger.