String Concatenation in Loop

ID

go.string_concat_in_loop

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Efficiency

Language

Go

Tags

code-style

Description

Reports building up a string by repeated concatenation inside a loop, either as s += x or s = s + x. Each concatenation allocates a new backing array and copies the accumulated bytes, turning a linear build into a quadratic one.

Rationale

Go strings are immutable. Every + or += on a string produces a brand-new string by allocating a fresh byte array and copying the old contents plus the new fragment. Inside a loop this is O(n²) in both allocations and bytes copied. Only the accumulating shapes are flagged (the left-hand side must reappear on the right-hand side), and the target must resolve to type string, so numeric counters are not reported.

// Bad — quadratic allocation
var s string
for _, item := range items {
    s += item
}

Remediation

Use a strings.Builder (or bytes.Buffer), which grows a single backing array amortised:

// Good — linear allocation
var b strings.Builder
for _, item := range items {
    b.WriteString(item)
}
s := b.String()

When joining with a separator, strings.Join(items, sep) is simpler still.