Explain size classes, spans and allocation caches
Explain size classes, spans and allocation caches
In Go 1.23, small heap requests generally round up to a size class. A span (mspan) is a run of runtime pages; a small-object span contains slots for one class. The per-P mcache supplies free slots, mcentral supplies spans, and mheap supplies page runs. Refilling in batches reduces contention. The tiny allocator can combine some small pointer-free objects; large objects bypass the small-object caches. These are implementation details, not a public allocator API. A runtime page need not equal an OS page.
package main
import ( "fmt")
func round(n int, classes []int) (int, bool) { for _, c := range classes { if n > 0 && n <= c { return c, true } } return 0, false}func main() { classes := []int{8, 16, 32, 64} for _, n := range []int{9, 31, 65} { v, ok := round(n, classes) fmt.Println(v, ok) }}This toy model deliberately uses only four classes, not the real allocator table. A 9-byte request uses a 16-byte slot in the model. The gap between requested size and slot capacity is internal fragmentation. Real sizes are affected by metadata and allocation paths. Check the versioned runtime source rather than coding around these toy numbers.
Expected output:
16 true32 true0 falseRead reported class boundaries
package main
import ( "fmt" "runtime")
func main() { var m runtime.MemStats runtime.ReadMemStats(&m) ok := false for _, c := range m.BySize { if c.Size >= 17 { ok = true break } } fmt.Println(ok)}BySize reports cumulative allocation and free counts for a subset of classes, with index zero unused. It does not cover all large allocations or provide the complete allocator table. ReadMemStats is a snapshot of the process; other allocations can affect it. Compare controlled workload runs rather than expecting an exact global counter increase.
Expected output:
trueTry it locally
For a toy 64-byte span and 16-byte slots, allocate three requests of 9 bytes; report free slots and internal waste in occupied slots.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Runtime allocation 04: Explain size classes, spans and allocation caches
Check the lesson objective before moving on.
What does mcache normally cache in Go 1.23?
Why is BySize not a complete allocation inventory?