a common mistake when using String Immutability
Fast recall
Quick revision
Core answer
Practical understanding of String Immutability.
Repeating a definition without saying when to use it.
Give one trade-off and say how you would test it.
Interview-ready guide
Interview answer
Each s += x copies the ENTIRE accumulated string into a fresh allocation, then appends. Ten appends copy 1+2+3+...+10 = 55 strings' worth — quadratic.
// BAD: O(n²)
var s string
for i := 0; i < 1000; i++ {
s += "chunk"
}
// GOOD: strings.Builder
var b strings.Builder
for i := 0; i < 1000; i++ {
b.WriteString("chunk")
}
s := b.String() // executed: one buffer, one final copyBuilder is a mutable byte slice internally (append's grow-by-double) with String() doing ONE copy at the end.
The family: strings.Builder for joining text; bytes.Buffer when you need bytes anyway; strings.Join for 'join with separator' (computes final size up front — zero realloc); fmt.Sprintf when formatting matters more than allocation (~3-5x slower — fine for UI, wrong in hot loops).
The detection test: any += or s = s + in a loop is O(n²) — flag it. The rewrite is always one of the four.
a common mistake when using String Immutability
Direct Answer
Each + allocates a new string and copies everything before it — N concatenations cost O(N²) copies. Use strings.Builder: one growing buffer, one final copy. Or strings.Join for the separator case.
Deep Dive & Architecture
The allocation arithmetic: appending k chunks of size c. First += copies c bytes. Second copies 2c. Third 3c. Total: c·k(k+1)/2 — O(k²) bytes copied for O(k·c) work.
Builder's mechanics: internally a []byte with append growth. WriteString appends (amortized O(1) per write); String() does ONE final copy. Grow(n) pre-allocates when the final size is knowable.
Why the compiler can't fix += automatically: Go's string is immutable, so s += x MUST produce a new string. The compiler folds some adjacent patterns, but the general loop case can't know the final size ahead — the quadratic cost is semantic, not an implementation accident. That's why the fix is an API (Builder) rather than a compiler pass.
The measurement: benchmarking += 10,000 times vs Builder — the += version is typically 100-1000x slower at that scale, entirely allocation. The Go 1.10 Builder release notes cite exactly this pattern.
Common Mistakes & Pitfalls
Repeating a definition without saying when to use it.
Check your understanding
Answer these without looking back at the article.
- What is String Immutability, and when would you use it?
- When would you use String Immutability in a real project?
- How would you compare String Immutability with an alternative?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.