Junior — Senior
Efficient string concatenation in a loop
livecode
Task condition
This example discusses common problems when building a string in a loop and ways to fix them.
func fn() {
result := ""
for i := 0; i < 100000; i++ {
result += fmt.Sprintf("%d", i)
}
}
Problems:
- The operation
result += ...creates a new string each time, copying the content, which leads to O(n²) time and high memory usage. - Inside the loop,
fmt.Sprintfis used, which is also costly as it formats the string.
Recommendations for improvement:
- Use
strings.Builder(orbytes.Buffer) – it can accumulate bytes without repeated copying. - Convert the number to a string without
Sprintf, for example usingstrconv.Itoa.
func fn() {
var b strings.Builder
b.Grow(600000) // approximate size estimate to avoid reallocations
for i := 0; i < 100000; i++ {
b.WriteString(strconv.Itoa(i))
}
result := b.String()
_ = result // use further
}
This approach reduces execution time and memory consumption to O(n).