Performance Comparison: String vs StringBuilder
You'll learn: How dramatically faster StringBuilder is compared to repeated String concatenation in real-world scenarios.
The Performance Gap
Because String is immutable, every concatenation creates a new String object and copies all existing characters plus the new ones. In a loop, this causes exponential growth in both time and memory usage.
StringBuilder, however, maintains an internal resizable character buffer. Each append() simply adds characters to this buffer—no new objects, no massive copying.
The Dramatic Difference
Imagine building a 10,000-word document:
String concatenation approach:
- Operation 1: Copy 1 word
- Operation 2: Copy 2 words
- Operation 3: Copy 3 words
- ...
- Operation 10,000: Copy 10,000 words
Total operations: roughly 50 million word copies!
StringBuilder approach:
- Each word is copied exactly once into the growing buffer
Total operations: 10,000 word copies.
Real-World Impact
In practice, concatenating 10,000 strings in a loop:
- String concatenation: Several seconds (with massive GC pressure)
- StringBuilder: A few milliseconds
The difference scales geometrically. With 50,000 iterations, String concatenation might take minutes or crash with OutOfMemoryError, while StringBuilder completes in under a second.
When It Matters
Single concatenations like "Hello" + " " + name are fine—the compiler optimizes these. But any loop or method that builds strings incrementally must use StringBuilder for acceptable performance.
Key Takeaway:
StringBuilder is orders of magnitude faster than repeated String concatenation because it avoids creating thousands of intermediate objects—always use it for string construction in loops or accumulation scenarios.