/performant-golang:go-perf-data-oriented-layoutfrom performant-golang
Guides data-oriented memory layout in Go — Struct-of-Arrays vs Array-of-Structs and when SoA wins (scan one field over many records, fewer cache lines), why []T beats []*T (a pointer slice scatters objects and adds GC scan work; []T is contiguous and noscan), replacing pointer-chasing lists/trees with int32 indices. Fires on cache-friendly layout, struct of arrays, slice of pointers is slow, data-oriented design. Routes field packing to go-perf-struct-layout, GC-scan to go-perf-allocator-internals, SIMD to go-perf-simd.
Ships in performant-golang. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
"Data dominates. If you've chosen the right data structures and organized things well, the algorithms will almost always be self-evident." — Rob Pike, Notes on Programming in C
This skill owns one lever: lay data out so the hot loop touches the fewest cache lines and the GC scans the fewest pointers. It is the cache-and-access-pattern peer of go-perf-struct-layout (which owns field ordering and padding within one struct). Correctness of slices/maps routes to go-slices-and-maps; the should-I-even-bother gate routes to go-perf-methodology — these are big wins only in hot, data-parallel loops a profile has already proven dominant, and they trade type-safety and readability for speed.
All Go below builds clean under gofmt and go vet on Go 1.26.
A modern core can do dozens of arithmetic ops in the time one DRAM miss costs. So the layout question is "how many cache lines does this loop drag in, and how predictably?" — not "how many instructions." go-perfbook puts the access-pattern rule plainly: "caches prefer the predictable access of scanning a slice to the effectively random access of chasing a pointer" (go-perfbook). Two consequences drive everything below:
go-perf-allocator-internals).When a loop reads one field across many elements, Array-of-Structs ([]Particle) drags every cold field of each element through cache; Struct-of-Arrays packs the hot field contiguously so the loop streams only what it uses. go-perfbook frames it as "SOA vs AOS layouts: row-major vs. column major" and asks the decisive question: "when you have an X, do you need another X or do you need a Y?" (go-perfbook). Iterating one field over many records → you need the next X, so pack the X's together.
// AoS: 48 bytes/elem. A one-field sum still pulls every cold field
// (Y, Z, velocities) through cache — wasted bandwidth.
type Particle struct {
X, Y, Z float64
VX, VY, VZ float64
}
func sumXAoS(ps []Particle) float64 {
var s float64
for i := range ps {
s += ps[i].X
}
return s
}
// SoA: X is packed contiguously. The loop streams one tight []float64,
// touches the minimum cache lines, and autovectorizes cleanly (→ go-perf-simd).
type Particles struct {
X, Y, Z []float64
VX, VY, VZ []float64
}
func sumXSoA(p Particles) float64 {
var s float64
for _, x := range p.X {
s += x
}
return s
}
Measured (Go 1.26, Ryzen 5950X, summing one field over 2²⁰ elements): for the 48-byte Particle above, SoA ran ~2.83 ms vs AoS ~3.5 ms (~1.2×). Widen the struct to 128 bytes (one hot field + 15 cold) and the gap opens to ~1.7× (AoS ~4.9 ms → SoA ~2.85 ms). The tell is in the shape: SoA's time is flat (~2.85 ms) regardless of struct width because it always streams the same packed array; AoS gets slower the more cold data each element carries. SoA wins exactly in proportion to the cold bytes you stop dragging — so it's worth it for wide records iterated field-wise, and pointless when the loop reads most fields of each element anyway.
[]T vs []*T — a slice of pointers is two penalties[]*Account stores contiguous headers, but each element is a separate heap object reached by an indirection. That is random access (cache misses on every dereference) and a slice full of pointers the GC must scan. []Account lays the values out contiguously, prefetches predictably, and — if Account is pointer-free — the whole backing array is noscan.
type Account struct {
Balance int64
ID int64 // pointer-free → []Account is a noscan span
}
func totalPtr(as []*Account) int64 { // scattered heap objects + GC scans every *Account
var t int64
for _, a := range as {
t += a.Balance
}
return t
}
func totalVal(as []Account) int64 { // contiguous, prefetch-friendly, noscan
var t int64
for i := range as {
t += as[i].Balance
}
return t
}
The GC Guide makes the scan cost explicit: "Pointer-free values are segregated from other values. As a result, it may be advantageous to eliminate pointers from data structures that do not strictly need them, as this reduces the cache pressure the GC exerts on the program" (GC Guide). Prefer []T of values; reach for []*T only when elements are large, individually mutated through shared aliases, or genuinely polymorphic.
Linked lists and pointer trees are the worst case: every node is a separate heap allocation, every link is a GC-scanned pointer, and traversal is a chain of cache misses. The fix is indices as pointers — keep all nodes in one contiguous []Node and link them by int32 offset. The slice is pointer-free (noscan), dense, and prefetch-friendly. The GC Guide endorses exactly this: "the GC must interact with nearly every pointer it sees, so using indices into a[n] slice, for example, instead of pointers, can aid in reducing GC costs," and "data structures that rely on indices over pointer values, while less well-typed, may perform better" (GC Guide).
// Pointer tree: each child is a heap object and a scanned pointer; random-access misses.
type NodeP struct {
Val int64
Left, Right *NodeP
}
// Index tree: all nodes in one noscan []Node; -1 is the nil sentinel.
type Node struct {
Val int64
Left, Right int32 // index into the backing slice; -1 == none
}
type Tree struct{ nodes []Node }
func (t *Tree) add(val int64) int32 {
t.nodes = append(t.nodes, Node{Val: val, Left: -1, Right: -1})
return int32(len(t.nodes) - 1)
}
int32 handles also halve the link size versus 64-bit pointers, packing more nodes per cache line. Measured framing matters here — the same guide warns this "is only worth doing if it's clear that the object graph is complex and the GC is spending a lot of time marking and scanning" (GC Guide). Confirm with a heap profile / GC trace before trading away *T type-safety; route the judgment to go-perf-methodology.
The same idea generalizes to allocation-free reuse:
[]T instead of container/list (which allocates a node and stores interface-boxed pointers per element). Contiguous, pointer-free, zero per-op allocation.[]T and hand out int32 handles instead of *T. The slab is dense and noscan; freeing a whole short-lived graph is one s.buf = s.buf[:0] that keeps the capacity — no per-node GC churn (slice reuse mechanics → go-perf-slices).// Slab: int32 handles, not *Node. Dense, noscan, freed en masse by reslicing.
type Slab struct{ buf []Node }
func (s *Slab) alloc(n Node) int32 {
s.buf = append(s.buf, n)
return int32(len(s.buf) - 1)
}
func (s *Slab) get(h int32) *Node { return &s.buf[h] }
func (s *Slab) reset() { s.buf = s.buf[:0] } // reuse capacity, no GC work
One caveat the index model buys you: a handle stays valid across a growslice, whereas a *Node into s.buf dangles after the backing array moves — so don't hold *Node across an alloc.
When several passes each touch the same large dataset, fuse them: do all the work on a block while it is resident in L1/L2 before moving on, instead of streaming the whole array once per pass. go-perfbook notes "iterating in batches over data structures can be much faster" (go-perfbook). The flip side is the lookup-table trap — precomputed tables can lose to recomputation: "It's very easy for lookup tables to be 'far away' in memory (and therefore expensive to access) making it faster to just recompute a value every time it's needed" (go-perfbook). A cache miss costs more than a handful of ALU ops, so a "fast" table that lives in cold memory can be slower than the arithmetic it replaced.
go-perf-methodology.[]*T for a collection of small values you iterate — it scatters the heap and adds GC scan work; use []T (GC Guide).*T into a slab/slice across an append — a growslice moves the backing array and dangles the pointer; hold the int32 handle instead (§5).container/list/container/ring on a hot path — per-node allocation and interface boxing; a slice-backed ring buffer is contiguous and allocation-free (§5).This plugin (go-perf-* depth):
go-perf-struct-layout — field ordering, alignment, and padding within a single struct; fieldalignment; pointer-free structs.go-perf-allocator-internals — noscan vs scan spans, size classes, and what makes a span GC-free; the allocator path behind "noscan."go-perf-slices — growslice, make([]T, 0, n) prealloc, s = s[:0] reuse, slice-backed ring buffers as a throughput lever.go-perf-simd — vectorizing the tight SoA loop SoA makes possible (GOEXPERIMENT=simd, 1.26).go-perf-bounds-check-elimination — dropping the per-iteration bounds check in the hot index loop.go-perf-false-sharing — when concurrent per-shard fields share a cache line (a different cache problem).go-perf-methodology — the measure-first gate: is this loop actually the bottleneck, and did the relayout measurably help?Parent / sibling marketplace (go-* correctness):
go-slices-and-maps — slice aliasing, append semantics, 3-index slices, Clone/Clip, nil maps — the correctness layer under the perf depth here.Data-layout anti-patterns in LLM-generated Go, each with a wrong/right contrast and citations:
Source provenance for every claim in this skill:
What SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
npx claudepluginhub ctoth/golang-skills-plugin --plugin performant-golang34 skills in this plugin
/go-perf-allocator-internalsWhat a Go heap allocation costs — the ~70 size classes and rounding waste (unsafe.Sizeof vs real slot), the tiny allocator packing sub-16B pointer-free objects, the lock-free per-P mcache → mcentral → mheap hierarchy, and scannable vs noscan spans (pointer-free objects cut GC cost; "1 alloc/op" hides different costs). Fires on "still slow after removing allocs", "reduce GC pressure", "size class", "how does Go allocate". Routes to go-perf-escape-analysis, go-perf-sync-pool, go-perf-gc-tuning, go-perf-struct-layout./go-perf-atomics-vs-locksGuides the atomics-vs-locks performance tradeoff in Go — typed sync/atomic ops (atomic.Int64/Pointer/Bool, 1.19) are a single CAS-style instruction, cheaper than a mutex uncontended but still cache-line-bouncing when contended; sync.Mutex's fast path is itself a CAS that only parks the goroutine when contended; RWMutex wins only for long read sections and is slower (scales worse) than a plain Mutex for short ones; the atomic.Pointer copy-on-write config swap; when lock-free isn't worth the correctness risk. Fires on "atomic vs mutex", "is RWMutex faster", "lock-free counter", "reduce locking overhead", "atomic.Pointer config". Routes copylock/atomic-API correctness to go-sync-primitives, memory ordering to go-race-and-memory-model, measuring to go-perf-block-mutex-profiles./go-perf-audience-and-tradeoffsGuides framing a Go performance decision by audience — the same change is right for one and wrong for another: the library author who can't profile callers and must not pessimize the common case (offer AppendXxx/[]byte forms, no unsafe in the API), the app developer who can profile and optimizes the proven hot path, the SRE who needs the code diagnosable (pprof labels, metrics, GOMEMLIMIT), the next reader who pays for clever micro-opts; the clarity-vs-speed through-line. Fires on "should a library do this", "is this worth optimizing for my users", "make this diagnosable", "premature optimization vs pessimization", "who am I optimizing for". Routes the policy root to go-idiomatic-discipline, measure-first to go-perf-methodology./go-perf-benchmarking-statisticsGuides trustworthy Go benchmark measurement at the command level — running each side with -count≥10 into old.txt/new.txt and feeding both to benchstat, reading its ± confidence interval, p-value (Mann–Whitney U), geomean, and the "~" no-significant-difference result, choosing the right unit (b.SetBytes for MB/s, b.ReportMetric for custom throughput), grouping a matrix with -col/-row/-filter, building a reproducible environment (perflock's 90% governor + serialization, frequency scaling. Auto-invokes when comparing benchmark runs, running benchstat, writing a perf A/B, or stabilizing a bench machine, and on "is this benchmark result real", "compare these benchmarks", "did this actually get faster", "my benchmark is noisy", "set up a perf regression test". Routes benchmark loop mechanics (for b.Loop, the sink/DCE trap, ResetTimer, RunParallel) to go-testing-advanced and the why-one-run-lies concept to go-perf-methodology./go-perf-block-mutex-profilesGuides Go contention diagnosis at depth — the block, mutex, and goroutine profiles, why block/mutex are OFF by default and read empty until runtime.SetBlockProfileRate (nanoseconds, 1=everything) / runtime.SetMutexProfileFraction (1/n sampled) are set, the overhead tradeoff, reading delay-vs-contention in pprof, and the goroutine profile for leak and pile-up detection. Auto-invokes on "why is this contended", "diagnose lock contention", "goroutine leak", "my mutex is slow", "profile blocking", "goroutines are piling up". Routes the fix to go-perf-contention-and-sharding / go-perf-atomics-vs-locks, sync correctness to go-sync-primitives, CPU/heap to go-perf-pprof-profiling./go-perf-bounds-check-eliminationGuides bounds-check elimination (BCE) in Go — the compiler checks every slice/array index and the SSA pass removes the ones it proves redundant. Covers seeing surviving checks with go build -gcflags="-d=ssa/check_bce/debug=1", prover-friendly idioms (the _ = b[n-1] / b = b[:n] hint, range loops, constant vs variable offsets), the inlining link, and why -B is a footgun not a fix. Fires on "eliminate bounds checks", "why is this loop slow", "bounds check in hot loop", "optimize this numeric loop". Routes should-I to go-perf-methodology, slices to go-perf-slices.