StringBuffer
and StringBuilder
are both Java classes for creating and manipulating mutable sequences of characters, but they differ in thread safety and performance.
Here’s a breakdown:
Feature | StringBuffer | StringBuilder |
---|---|---|
Mutability | Mutable (like StringBuilder ) | Mutable (like StringBuffer ) |
Thread Safety | Yes — methods are synchronized, so multiple threads can use the same object without corrupting data | No — methods are not synchronized, so unsafe in multi-threaded contexts |
Performance | Slower than StringBuilder because synchronization adds overhead | Faster than StringBuffer because no synchronization overhead |
Introduced In | Java 1.0 | Java 5 |
Usage | Use when multiple threads need to modify the same string object | Use when only one thread will be modifying the string |
Example:
// StringBuffer example (thread-safe)
StringBuffer sbf = new StringBuffer("Hello");
sbf.append(" World");
System.out.println(sbf); // Hello World
// StringBuilder example (faster, not thread-safe)
StringBuilder sbd = new StringBuilder("Hello");
sbd.append(" World");
System.out.println(sbd); // Hello World
Rule of Thumb:
- Single-threaded → Use StringBuilder (better performance).
- Multi-threaded → Use StringBuffer (safety over speed).