ออบเจ็กต์ StringBuffer ใช้งานได้ปลอดภัยในสภาพแวดล้อม multi-threaded ที่หลาย thread อาจพยายามเข้าถึง StringBuffer เดียวกันพร้อมกัน ในขณะที่ StringBuilder เป็นตัวแทนของ StringBuffer ที่ thread-safe และทำงานเร็วกว่ามาก เนื่องจากไม่มีเมธอด synchronized หากทำการดำเนินการ String มากใน single thread จะได้ประสิทธิภาพที่ดีกว่ามากเมื่อใช้ StringBuilder
ตัวอย่าง
public class CompareBuilderwithBufferTest {
public static void main(String[] args) {
stringBufferTest();
stringBuilderTest();
}
public static void stringBufferTest() {
long startTime = System.nanoTime();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 1000; i++) {
sb.append('a');
}
System.out.println("StringBuffer test: " + (System.nanoTime() - startTime));
}
public static void stringBuilderTest() {
long startTime = System.nanoTime();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.append('a');
}
System.out.println("StringBuilder test: " + (System.nanoTime() - startTime));
}
}
Output
StringBuffer test: 192595 StringBuilder test: 85733