go 17 lines · 1 tab

sync.Pool for bytes.Buffer to reduce allocations in hot paths

Leah Thompson Jan 2026
1 tab
package pools

import (
  "bytes"
  "sync"
)

var bufPool = sync.Pool{
  New: func() any { return new(bytes.Buffer) },
}

func WithBuffer(fn func(*bytes.Buffer) error) error {
  b := bufPool.Get().(*bytes.Buffer)
  b.Reset()
  defer bufPool.Put(b)
  return fn(b)
}
1 file · go Explain with highlit

For high-throughput endpoints that serialize JSON or build strings repeatedly, allocations can become a real cost. sync.Pool is a pragmatic tool for reusing temporary buffers without manual free lists. The key is to treat pooled objects as ephemeral: get a buffer, Reset it, use it, and return it. Never store pooled pointers long-term. The pool can drop objects at any time, which is fine because it’s a performance hint, not a correctness mechanism. In production, I use this for response building, log formatting, and compression pipelines where buffers are short-lived and frequently reused. It won’t fix slow algorithms, but it can significantly reduce allocs/op once you’ve identified a hot loop. Pair it with benchmarks so you can confirm the improvement.


Related snips

Share this code

Here's the card — post it anywhere.

sync.Pool for bytes.Buffer to reduce allocations in hot paths — share card
Link copied