Skip to content

String Concat In Loop (ARCH5070)

Key go.performance.string-concat-in-loop · Severity warning · Category performance

Strings are immutable in Go; concatenating with += inside a loop allocates and copies a new buffer on every iteration, yielding O(n^2) cost. Use a strings.Builder instead.

func join(items []string) string {
var result string
for _, item := range items {
result += item + ","
}
return result
}
func join(items []string) string {
var b strings.Builder
for _, item := range items {
b.WriteString(item)
b.WriteByte(',')
}
return b.String()
}

Accumulate into a single strings.Builder instead of using += in the loop.