Strings Builder Efficient Assembly

Assemble large strings with strings.Builder instead of += concatenation, so growth is amortized instead of quadratic buffer copies.

GoData Integrity

Code

gosnippet
28 lines
package main

import (
	"fmt"
	"strconv"
	"strings"
)

func buildReport(rows map[string]int) string {
	var b strings.Builder
	// Grow 预分配:已知大致体量时避免反复扩容
	b.Grow(len(rows) * 24)

	for name, count := range rows {
		b.WriteString(name)
		b.WriteByte(':')
		b.WriteString(strconv.Itoa(count))
		b.WriteByte('\n')
	}
	return b.String()
}

func main() {
	rows := map[string]int{"requests": 1200, "errors": 3, "timeouts": 1}
	report := buildReport(rows)
	fmt.Print(report)
	fmt.Println("total bytes:", len(report))
}

Beneath the surface

Structurally, expect the functions buildReport and main and nothing else.

Iteration happens inside for name, count := range rows — everything outside it runs once.

Applying it

Entry signature: func buildReport(rows map[string]int) string

The demo output is labeled (total bytes:), so the output doubles as a step-by-step trace of what the file did.

Running the file executes main, which drives buildReport in order.

Statements that matter

func buildReport(rows map[string]int) string {
var b strings.Builder
// Grow 预分配:已知大致体量时避免反复扩容
b.Grow(len(rows) * 24)
for name, count := range rows {
b.WriteString(name)
b.WriteByte(':')
b.WriteString(strconv.Itoa(count))
b.WriteByte('\n')
}
return b.String()
}
func main() {
rows := map[string]int{"requests": 1200, "errors": 3, "timeouts": 1}
report := buildReport(rows)
fmt.Print(report)
fmt.Println("total bytes:", len(report))
}

Interactive Tools for This Topic

FAQ

What does Strings Builder Efficient Assembly print when run?
Invoke the file as-is — the `total bytes:` prefixes identify which step printed each line.