Lesson 27 · Senior Go backend engineering
sync.Pool & memory layout
When reuse helps, and why the shape of a struct can affect real backend costs.
Your win: explain when sync.Pool is appropriate, when it is not, and why struct field order can matter once you have enough data in memory that every wasted byte gets multiplied.
sync.Pool is for temporary reuse, not ownership. Struct alignment is about how the compiler lays fields out in memory, which can quietly change how large each value becomes.
Two separate ideas that meet in performance work
These topics feel different, but they meet in the same place: the moment you are no longer asking “does this code work?” and start asking “what does this code cost when it runs a million times?”
sync.Pool: what it is for
- Reusing short-lived buffers or helper objects
- Reducing allocation churn on hot paths
- Helping only after measurement proves allocation pressure matters
It is not a general cache, a lifetime manager, or a place to hide correctness rules.
sync.Pool usage in generator code. That is a helpful anchor: the pool exists to reuse an expensive helper object, not to become shared application state that other code must reason about semantically.
Struct alignment
type Bad struct {
flag bool
n int64
b bool
}
type Better struct {
n int64
flag bool
b bool
}
Reordering fields can shrink the struct because the compiler inserts padding to satisfy alignment rules. When one value is tiny, you rarely care. When millions of values are resident, you suddenly do.
sync.Pool is usually a hot-path optimization, not a default design pattern. Both are “after measurement” topics.
sync.Pool because “allocations are bad.” Pools add complexity and can make ownership less obvious. Measure first, then optimize the hot path you can prove matters.
Diagnostics + performance tooling
Use the standard toolchain to find out whether allocation churn or memory density is actually your bottleneck before changing code shape.
→ go.dev/doc/diagnostics
→ go.dev/blog/profiling-go-programs
Check yourself (from memory)
Q1. sync.Pool is best for…
Q2. Why can field order matter in a struct?
sync.Pool?unsafe.Sizeof demo that shows exactly how field reordering changes struct size? Ask me.
Sources. Go Diagnostics; Profiling Go Programs.