Memory Implications of Repeated Concatenation
You'll learn why repeatedly concatenating Strings in loops can create serious memory overhead and performance problems.
The Hidden Cost of += in Loops
Because Strings are immutable in Java, every time you use the += operator on a String, you're not modifying the original—you're creating an entirely new String object. When this happens inside a loop, the memory cost multiplies dramatically.
Consider building a String by concatenating in a loop:
String result = "";
for (int i = 0; i < 1000; i++) {
result += i + ","; // Creates a new String object each iteration!
}
This innocent-looking code creates 1,000 intermediate String objects. On the first iteration, you create a String with "0,". On the second, Java creates a new String containing "0,1,". On the third, another new String with "0,1,2,". Each previous String becomes garbage immediately.
The Memory Explosion
If you're concatenating N Strings in a loop, you don't just create N objects—you create roughly N × (N+1) / 2 intermediate objects. With 1,000 iterations, that's about half a million character copies happening behind the scenes!
Analogy: Imagine rewriting an entire book from scratch every time you want to add one new sentence. By the end, you've written the first chapter 100 times, the second chapter 99 times, and so on—exponentially wasteful.
Why This Matters
Each intermediate String occupies heap memory until garbage collection runs. In tight loops or with large Strings, this can:
- Trigger frequent garbage collection pauses
- Exhaust available memory
- Drastically slow down your application
Key Takeaway: Repeated String concatenation with += in loops creates a cascade of temporary String objects, causing quadratic memory overhead and severe performance degradation—avoid it for anything beyond trivial cases.