Mutable character buffers, capacity expansion, loop concatenation pitfalls, and thread-safety differences
Because Java String instances are immutable, performing repeated string modifications or concatenations using the + operator generates redundant intermediate String objects on the heap. StringBuilder and StringBuffer provide resizable, mutable character buffers to assemble text with optimal performance.
A common performance bug in Java is concatenating strings inside a loop using +:
StringConcatTrap.java
// ANTI-PATTERN: O(n^2) Time and Space OverheadString result = "";for (int i = 0; i < 10000; i++) { result += i; // Allocates a brand-new String object and copies all characters on every iteration!}
Why + in loops destroys performance: Each += copies the entire accumulated character
buffer into a new heap object. For n iterations, this allocates (1 + 2 + ... + n) = O(n^2) total
characters, triggering heavy Garbage Collection pauses.
Default choice for single-threaded code, algorithms, and local variables
Legacy applications with shared multi-threaded logging buffers
Why StringBuffer is Rarely Needed Today: In modern Java architectures, string construction is
almost exclusively local to a single thread or method stack. Using StringBuffer imposes
unnecessary synchronization overhead.
You do not need to manually construct a StringBuilder.
Since Java 9, the compiler replaces simple string concatenation with invokedynamic calls backed by java.lang.invoke.StringConcatFactory. The JVM dynamically crafts the most optimal strategy at runtime without creating redundant intermediate objects.