Cut Allocations With Pre-Sizing and sync.Pool
Reduce heap allocations using pre-sized slices and sync.Pool for reusable buffers, and confirm gains with benchmarks. After this, hot paths allocate far less garbage.
Course content
Sign in to save your progress.
-
Bounded Concurrency and Worker Pools
-
Bound Concurrency With a Worker Pool
-
Coordinate Shared State With sync.Mutex and atomic
-
-
-
Memory, Allocations, and Benchmarking
-
Measure Speed and Allocations With go test -bench
-
Cut Allocations With Pre-Sizing and sync.Pool
-
-
-
Profiling and Diagnostics
-
Find CPU and Heap Hotspots With pprof
-
Catch Goroutine Leaks and Slow Tests Early
-
-
-
Resilience and Defensive HTTP
-
Add Retries With Backoff and Jitter
-
Protect Endpoints With Rate Limiting and Panic Recovery
-
-
-
Production Builds and Containers
-
Embed Static Assets and Version Info With embed and ldflags
-
Ship a Multi-Stage Scratch Go Container
-
-
-
Fuzzing, GC Tuning, Tracing, and Reflection
-
Fuzz Testing Parsers and Decoders With go test -fuzz
-
Escape Analysis and GC Tuning (-gcflags="-m", GOGC, GOMEMLIMIT)
-
Execution Tracing and Block/Mutex Contention Profiling
-
Reflection, Struct Tags, and go generate
-
-
In a high-throughput API or audit-event service formatting thousands of JSON lines per second, two allocation habits quietly dominate garbage-collector CPU time: growing slices and strings repeatedly from capacity zero, and allocating a fresh 4 KB bytes.Buffer on every single request.
Pre-sizing (make([]T, 0, n) and strings.Builder.Grow) fixes allocations inside a single call, while sync.Pool reuses temporary buffers across requests—dropping heap churn by up to 100× when paired with two mandatory safety rules: Reset() and a max-capacity cap.
Skip ahead
If you already pre-size slices/builders and pool *bytes.Buffer safely with Reset() and a 64 KB cap before Put, take the section quiz or move on to "Find CPU and Heap Hotspots With pprof."
Experiment 1: Pre-sizing a strings.Builder eliminates 98% of bytes allocated
Before reaching for sync.Pool, check whether a loop is allocating dozens of intermediate strings or slices. Compare concatenating 200 items with += versus a pre-grown strings.Builder:
func buildSlow(n int) string {
s := ""
for i := range n {
s += fmt.Sprintf("item-%d,", i)
}
return s
}
func buildFast(n int) string {
var b strings.Builder
b.Grow(n * 10)
for i := range n {
b.WriteString("item-")
b.WriteString(fmt.Sprint(i))
b.WriteByte(',')
}
return b.String()
}
$ go test -bench=BenchmarkBuild -benchmem -benchtime=200ms
BenchmarkBuildSlow-2 5755 67214 ns/op 176536 B/op 399 allocs/op
BenchmarkBuildFast-2 21714 10256 ns/op 2549 B/op 191 allocs/op
Because Go strings are immutable, s += ... copied the entire growing string on every iteration—allocating 176,536 B/op just to build a ~2 KB result! Pre-sizing strings.Builder cut memory per call by ~69×.
Experiment 2: Reusing 4 KB buffers across requests with sync.Pool
Now suppose an audit logger writes a structured JSON event per request into a 4 KB buffer. Allocating a fresh buffer every time creates 4 KB of heap garbage per request; reusing buffers with sync.Pool drops that to almost zero:
package eventlog
import (
"bytes"
"fmt"
"io"
"sync"
"testing"
)
var bufPool = sync.Pool{
New: func() any { return new(bytes.Buffer) },
}
func formatAuditEvent(w io.Writer, userID, action string, padding []byte) error {
b := bufPool.Get().(*bytes.Buffer)
b.Reset()
fmt.Fprintf(b, `{"user":%q,"action":%q,"pad":%d}`+"\n", userID, action, len(padding))
_, err := w.Write(b.Bytes())
if b.Cap() <= 64*1024 {
bufPool.Put(b)
}
return err
}
func TestPoolIsolatesUsers(t *testing.T) {
var out1, out2 bytes.Buffer
_ = formatAuditEvent(&out1, "alice", "login", nil)
_ = formatAuditEvent(&out2, "bob", "logout", nil)
if bytes.Contains(out2.Bytes(), []byte("alice")) {
t.Fatalf("leaked alice into bob: %s", out2.String())
}
}
$ go test -v -bench=. -benchmem -benchtime=200ms .
=== RUN TestPoolIsolatesUsers
--- PASS: TestPoolIsolatesUsers (0.00s)
BenchmarkFormatFresh-2 450516 615.4 ns/op 4152 B/op 3 allocs/op
BenchmarkFormatPooled-2 2111535 114.9 ns/op 40 B/op 3 allocs/op
Heap bytes dropped from 4,152 B/op to 40 B/op (~100× less churn) and runtime jumped 5.4× faster.
Experiment 3: Why omitting Reset() or the 64 KB cap causes production incidents
- Skipping
b.Reset(): WithoutReset()right afterGet(),bob's audit event appends straight ontoalice's leftover bytes—leaking one user's data into another user's output!Reset()sets length to0while keeping the backing array ready for reuse. - Skipping
if b.Cap() <= 64*1024: If 99.9% of events are 4 KB and one rare bulk export grows a buffer to 32 MB, putting that 32 MB buffer back intobufPoolpins 32 MB in RAM until two consecutive GC cycles evict it. Dropping oversized buffers lets GC reclaim spikes immediately.
Common mistakes
- Returning
b.Bytes()after callingbufPool.Put(b):b.Bytes()aliases the buffer's internal backing array—the next goroutine callingGet()will overwrite those exact bytes underneath your caller! Write to anio.Writeror copy to astringbefore callingPut. - Using
sync.Poolfor database connections or as a cache: The garbage collector can silently evict any entry insync.Poolat any time without callingClose(). - Pooling tiny 16-byte allocations:
Get()/Put()overhead can match or exceed a small stack allocation—benchmark with-benchmemfirst.
💡 Tip
Always pool a pointer (like *bytes.Buffer or *[]byte), never a bare slice value []byte—passing a slice value to Put(any) allocates a 24-byte interface header box on every single Put.
What happens if you skip this step
Leaving string concatenation and unpooled multi-KB buffers on hot endpoints keeps GC CPU high; using sync.Pool without Reset() and a capacity cap either corrupts user responses with stale bytes or pins huge outlier buffers in RAM.
A handler grabs a *bytes.Buffer from sync.Pool, writes JSON into it, calls bufPool.Put(b) inside a defer, and returns b.Bytes() to the caller. Why is that a severe data-corruption bug under concurrent traffic?
About
Reduce heap allocations using pre-sized slices and sync.Pool for reusable buffers, and confirm gains with benchmarks. After this, hot paths allocate far less garbage.
- Duration
- 5 min
- Last update
- 11/27/2026
Comments
Sign in to commentNo comments yet.