Sync Pool Byte Buffer Reuse
Recycle byte buffers with sync.Pool to cut allocation churn in hot paths, using Get/Put discipline and clearing on store.
Code
package main
import (
"bytes"
"fmt"
"sync"
)
var bufferPool = sync.Pool{
New: func() interface{} {
return new(bytes.Buffer) // 池空时的兜底构造
},
}
func renderJSON(name string, score int) string {
buf := bufferPool.Get().(*bytes.Buffer)
defer func() {
buf.Reset() // 必须清零,防止跨使用者数据泄漏
bufferPool.Put(buf) // 归还前重置容量状态
}()
buf.WriteString("{\"name\":\"")
buf.WriteString(name)
buf.WriteString("\",\"score\":")
fmt.Fprintf(buf, "%d}", score)
return buf.String()
}
func main() {
results := make([]string, 0, 8)
var wg sync.WaitGroup
for i := 0; i < 8; i++ {
wg.Add(1)
go func(n int) {
defer wg.Done()
results = append(results[:n:n], renderJSON(fmt.Sprintf("user-%d", n), n*10))
}(i)
}
wg.Wait()
for _, r := range results {
fmt.Println(r)
}
}How it works
Sync Pool Byte Buffer Reuse comes down to the functions renderJSON and main.
Iteration happens inside for i := 0; i < 8; i++ — everything outside it runs once. The task is handed to a goroutine and runs concurrently. defer inverts the usual order — register now, run at return — which is why cleanup cannot be skipped.
Putting it to use
The primary signature is func renderJSON(name string, score int) string
There are 1 call inside main — renderJSON — executed top to bottom.
Core lines
results = append(results[:n:n], renderJSON(fmt.Sprintf("user-%d", n), n*10))
var bufferPool = sync.Pool{
New: func() interface{} {
return new(bytes.Buffer) // 池空时的兜底构造
},
}
for _, r := range results {
fmt.Println(r)
}
Interactive Tools for This Topic
Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.HAR Waterfall AnalyzerInspect HTTP Archive (HAR 1.2) JSON files locally to summarize total requests, status codes, MIME types, slowest calls, and timing waterfalls.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.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.
FAQ
- How do you run Sync Pool Byte Buffer Reuse?
- Direct execution is enough; the script has no external requirements.
Report a problem with this exampleOpens a pre-filled issue on GitHub.