Why should you use strings.Builder for concatenating strings in a loop instead of the + operator?
Last updated
Because strings are immutable in Go, each + concatenation allocates a brand-new string and copies all existing bytes, making a loop O(n²); strings.Builder appends into a growable buffer and avoids those repeated allocations and copies.
Strings are immutable:
a + bcannot modifyain place; it must allocate a new string and copy both operands.In a loop this re-copies the accumulated result every iteration: quadratic time and heavy garbage.
strings.Builder amortizes growth:
It writes into an internal
[]bytethat grows like a slice, so total work is amortized O(n).String()returns the result without copying the buffer (uses an unsafe internal trick).
Extra tips:
Call
Grow(n)if you know the final size to preallocate.For a known small fixed number of pieces,
+orstrings.Joinis fine; the win is in loops.
[lang:go]
var b strings.Builder
for i := 0; i < 1000; i++ {
b.WriteString("x") // appends into a growable buffer
}
result := b.String() // no full copy