Slices, maps and strings · 3 MIN READ

Concatenating in a loop repeatedly rebuilds a string

Use strings.Builder for repeated construction without rebuilding the prefix.

Strings are immutable. Repeated s += piece operations in a growing loop can copy the accumulated prefix repeatedly, producing quadratic work as the output grows. Small fixed concatenations may be optimized differently, so measure the actual workload.

strings.Builder accumulates text in a growing buffer and exposes the result with String. strings.Join is a simpler choice when all pieces are already collected. A non-zero Builder must not be copied.

SEE THE IDEA

Accumulate bytes before producing the string

  1. 01

    Builder

    go
    var b strings.Builder

    The zero value is ready

  2. 02

    Append

    go
    b.WriteString(part)

    Grow the accumulated buffer

  3. 03

    Finish

    go
    result := b.String()

    Read the completed string

A builder avoids repeatedly concatenating an ever-growing prefix.

In practice

Use strings.Join when all pieces are already collected; use strings.Builder when generating text step by step. Grow can reserve a known size, but it is optional. A builder is for text, while bytes.Buffer is useful when both byte-oriented reads and writes are needed.

Watch out

Do not copy a non-zero strings.Builder. Keep one owner and measure before adding speculative capacity estimates.

Official reference ↗

Work through the exercise

go
package main

// Repeat joins n copies of word with a single space between them.
// Build it without concatenating in the loop.
func Repeat(word string, n int) string {
	out := ""
	for i := 0; i < n; i++ {
		out += word + " "
	}
	return out
}

func main() {}
Try it yourself

Trace each value and write down your reasoning. Copy the source into GopherForge or your local Go environment to compile and check it. This web page does not execute your code or send it to a compiler service.

Progress stays in this browser. No account needed.