Strings Builder Efficient Assembly
Assemble large strings with strings.Builder instead of += concatenation, so growth is amortized instead of quadratic buffer copies.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HAR Waterfall AnalyzerInspect HTTP Archive (HAR 1.2) JSON files locally to summarize total requests, status codes, MIME types, slowest calls, and timing waterfalls.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.