sync.Pool
sync.Pool is a concurrent free-list of temporary objects. Get returns a stored value or calls New. Put returns a value for later Get. The garbage collector may discard pooled items at any time.
Detailed Explanation
You allocate a []byte buffer on every request, and profiles show allocation in that make. A Pool lets one request Put the buffer and the next Get reuse it. That cuts GC pressure when the same size is needed at a high rate.
Not a cache of important data. Anything in a Pool can vanish between Put and Get when a GC runs. Do not store database connections or anything you cannot recreate. New must be able to build a fresh object every time.
Reset on Get. A previous user may have left data in the []byte or struct. Reset len to 0, or zero fields, before you use it. Leaking a previous request's bytes into the next response is a security bug.
Type assertion. Get returns any. buf := pool.Get().(*bytes.Buffer) panics if New returned a different type. Keep one pool per type.
What it costs. A Pool helps when allocation rate is high and object size is non-trivial (bytes.Buffer, []byte of a few KiB). For small structs, pooling can be slower than allocating. Measure with testing.B and pprof. Do not pool because it looks like C++ object reuse; pool because the allocation profile said so.
Code Examples
package main
import (
"bytes"
"sync"
)
var bufPool = sync.Pool{
New: func() any { return new(bytes.Buffer) },
}
func use() string {
b := bufPool.Get().(*bytes.Buffer)
b.Reset()
defer bufPool.Put(b)
b.WriteString("ok")
return b.String() // copies; safe to Put after
}
func main() {
_ = use()
}var slPool = sync.Pool{
New: func() any {
s := make([]byte, 0, 1024)
return &s
},
}Common Gotchas
Using a buffer after `Put` races the next `Get`
`String()` copies; `Bytes()` shares the array — copy before `Put` if you return those bytes.
Pooled objects are not wiped by the runtime
reset them.
The GC can drop the whole pool
`Get` may always call `New` under memory pressure.
A zero `Pool` with nil `New` returns nil from `Get`
set `New` or handle nil.