간단한 소스로 확인에 들어간다
package codeplay;
public class StringBufferTime {
public static void main(String[] args) {
long start = System.currentTimeMillis();
String str = "a";
for (int i = 0; i < 300000; i++) {
str += "a";
}
StringBuffer sb = new StringBuffer("a");
for (int i = 0; i < 300000; i++) {
sb.append("a");
}
long end = System.currentTimeMillis();
System.out.println(end - start);
}
}
15694
package codeplay;
public class StringBuildTime {
public static void main(String[] args) {
long start = System.currentTimeMillis();
String str = "a";
for (int i = 0; i < 300000; i++) {
str += "a";
}
StringBuilder sb = new StringBuilder("a");
for (int i = 0; i < 300000; i++) {
sb.append("a");
}
long end = System.currentTimeMillis();
System.out.println(end - start);
}
}
15663
근소한 차이지만 StringBuilder가 빠르긴 하다
검색을 좀 해보니
스트링버퍼와 빌더의 차이는 스레드를 세이프하냐 안하냐의 차이라고 한다.
문자열 결합에 스레드 세이프가 필요한가?
라는 생각에서 만들어진것이 스트링 빌더 라고 함