Why should you use strings.Builder for concatenating strings in a loop instead of the + operator?

Last updated 20 June 2026

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 + b cannot modify a in 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 []byte that 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, + or strings.Join is 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

  • https://www.reddit.com/r/golang/comments/1ickq77/stringsbuilder_is_faster_on_writing_strings_then/
  • https://go.dev/blog/gofix
All Golang interview questions