Worlds, AI and multiplayer · 7 MIN READ

A 16.6 ms frame budget: measure allocations per update and make the steady state allocate nothing

Turn refresh rates into frame budgets, count allocations per update with testing.AllocsPerRun, remove per-frame slices, maps, closures and strings, and profile a game loop with pprof and execution traces.

At 60 frames per second each frame has about 16.6 ms for input, simulation, drawing and whatever the runtime needs. Go's garbage collector runs concurrently, but its work is paid for by your program: the more a game allocates per frame, the more often a cycle starts and the more CPU the collector takes from the loop. The useful goal is not zero allocations ever; it is an update that allocates nothing in steady state, verified by a number a test can check.

gamedev · A MAP OF THE IDEA

  1. Budget from refresh rate
  2. Count allocs per update
  3. Reuse loop-owned storage
  4. Profile, then tune GC

Useful when

  • A zero-allocation assertion catches regressions in CI.
  • Loop-owned buffers are deterministic and cache-friendly.

Watch out

  • Non-zero allocation counts change between Go releases.
  • sync.Pool may drop pooled objects at any GC cycle.

Implementation & operation cost: Scratch fields on the world, capacity planning at level load, and code that is slightly less obvious than allocating fresh values.

01

Where the 16.6 ms goes

Divide one second by the refresh rate: about 16.7 ms at 60 Hz, 8.3 ms at 120 Hz and 6.9 ms at 144 Hz. Ebitengine calls Update at the tick rate and Draw once per displayed frame, and both share that budget with the graphics driver and the operating system. A frame that misses its deadline is a visible hitch, and players notice a single 30 ms spike more than a steady 10 ms average. Allocation feeds that risk. The collector paces cycles by heap growth, so a loop that allocates a few megabytes per second starts cycles regularly; during a cycle, background workers take a share of the CPU and goroutines that keep allocating are charged assist work, which lands directly in your update. Reducing the allocation rate is therefore the first lever, and GOGC or GOMEMLIMIT tuning, covered by the GC budget lesson, comes after it.

02

Count allocations per update with testing.AllocsPerRun

testing.AllocsPerRun runs a function once to warm up, counts heap allocations over the requested number of runs and returns the integer average, with GOMAXPROCS set to 1 during the measurement. It works outside tests too, so the program uses it on paired implementations: a visibility query written the obvious way and one that reuses storage, deferred hit effects as closures and as values, and HUD text rebuilt every update versus cached. The two versions in each pair produce the same result; only their allocation behavior differs.

go
package main

import (
	"cmp"
	"fmt"
	"slices"
	"sort"
	"strconv"
	"testing"
	"time"
)

type Entity struct {
	ID    int
	X, Y  float64
	Alive bool
	HP    int
}

type Hit struct{ Attacker, Target, Damage int }

type World struct {
	Entities []Entity
	Score    int
	visible  []int    // scratch reused every update
	stamp    []int    // per-entity "seen in update N" marks instead of a map
	frame    int      // update counter used with stamp
	events   []Hit    // queued effects as plain values
	pending  []func() // the closure version, for comparison
}

func NewWorld(n int) *World {
	w := &World{Entities: make([]Entity, n), stamp: make([]int, n)}
	for i := range w.Entities {
		w.Entities[i] = Entity{ID: i, X: float64((i * 37) % 200), Y: float64(i % 50), Alive: i%7 != 0, HP: 100}
	}
	w.visible = make([]int, 0, n) // sized once, at level load
	w.events = make([]Hit, 0, n)
	w.pending = make([]func(), 0, n)
	return w
}

// VisibleFresh is the obvious version: a new slice, a new map and a capturing sort closure.
func (w *World) VisibleFresh(minX, maxX float64) []int {
	var ids []int
	seen := map[int]bool{}
	for _, e := range w.Entities {
		if e.Alive && e.X >= minX && e.X < maxX && !seen[e.ID] {
			seen[e.ID] = true
			ids = append(ids, e.ID)
		}
	}
	sort.Slice(ids, func(i, j int) bool { return w.Entities[ids[i]].X < w.Entities[ids[j]].X })
	return ids
}

// VisibleReuse produces the same result into storage the world already owns.
func (w *World) VisibleReuse(minX, maxX float64) []int {
	w.frame++
	w.visible = w.visible[:0]
	for _, e := range w.Entities {
		if e.Alive && e.X >= minX && e.X < maxX && w.stamp[e.ID] != w.frame {
			w.stamp[e.ID] = w.frame
			w.visible = append(w.visible, e.ID)
		}
	}
	slices.SortFunc(w.visible, func(a, b int) int {
		return cmp.Compare(w.Entities[a].X, w.Entities[b].X)
	})
	return w.visible
}

// QueueClosures defers each hit as a closure stored for later: every one escapes.
func (w *World) QueueClosures(hits int) {
	w.pending = w.pending[:0]
	for i := range hits {
		target := &w.Entities[i]
		damage := 3 + i%4
		w.pending = append(w.pending, func() { target.HP -= damage })
	}
	for _, f := range w.pending {
		f()
	}
}

// QueueValues defers the same hits as data and applies them in one loop.
func (w *World) QueueValues(hits int) {
	w.events = w.events[:0]
	for i := range hits {
		w.events = append(w.events, Hit{Attacker: -1, Target: i, Damage: 3 + i%4})
	}
	for _, h := range w.events {
		w.Entities[h.Target].HP -= h.Damage
	}
}

// HUD rebuilds its text only when the value it shows changes.
type HUD struct {
	score int
	text  string
}

func (h *HUD) Text(score int) string {
	if h.text == "" || score != h.score {
		h.score, h.text = score, "score "+strconv.Itoa(score)
	}
	return h.text
}

var (
	sink  []int
	label string
)

func main() {
	for _, hz := range []int{60, 120, 144} {
		fmt.Printf("frame budget at %d Hz: %v\n", hz, time.Second/time.Duration(hz))
	}
	w := NewWorld(500)
	fresh := w.VisibleFresh(40, 120)
	reused := w.VisibleReuse(40, 120)
	fmt.Printf("visible entities: %d, both versions agree: %t\n", len(reused), slices.Equal(fresh, reused))

	report := func(name string, f func()) {
		fmt.Printf("%-34s %3.0f allocs/update\n", name, testing.AllocsPerRun(200, f))
	}
	report("visible query, fresh slice+map:", func() { sink = w.VisibleFresh(40, 120) })
	report("visible query, reused scratch:", func() { sink = w.VisibleReuse(40, 120) })
	report("32 hits queued as closures:", func() { w.QueueClosures(32) })
	report("32 hits queued as values:", func() { w.QueueValues(32) })
	w.Score = 12345
	hud := &HUD{}
	report("HUD text rebuilt every update:", func() { label = fmt.Sprintf("score %d", w.Score) })
	report("HUD text cached until it changes:", func() { label = hud.Text(w.Score) })
}
Read the code

time.Second / time.Duration(hz) prints exact budgets. VisibleFresh allocates 22 times per call: append growing a nil slice to 173 elements, the map growing as IDs are inserted, and sort.Slice, which receives the slice as an interface and builds a reflection-based swapper. VisibleReuse truncates a slice sized at level load, replaces the map with a stamp slice compared against a frame counter and sorts with slices.SortFunc; its comparison closure captures w but does not escape, so it lives on the stack and the count is 0. QueueClosures stores 32 capturing closures in a slice for later, so each one escapes to the heap: exactly 32. QueueValues queues the same hits as structs: 0. fmt.Sprintf allocates twice, once to box the int into its ...any parameter and once for the new string, while the HUD cache rebuilds only when the score changes. Results go into package-level variables so the compiler cannot discard the work. The counts are stable for one toolchain but can change between Go releases as escape analysis improves.

03

Patterns that keep the steady state allocation-free

Size scratch slices when a level loads and reuse them with s = s[:0], so append writes into existing capacity. Replace per-frame sets with data the world already owns: a stamp slice, a bit set, or a long-lived map emptied with clear(m), which keeps its storage. Queue effects as plain structs processed in one loop instead of closures that capture entities; values are also easier to log, replay and send over the network. Closures are not the problem by themselves, escaping closures are: a closure passed to a function that only calls it, like the SortFunc comparator, stays on the stack. Watch for hidden boxing, because passing an int or a struct as any to fmt, a logger or an interface-typed event bus can allocate, and so can converting []byte to string for text. Build HUD strings when the value changes, not every frame. To see why a line allocates, go build -gcflags=-m prints the compiler's escape decisions.

04

sync.Pool or a free list owned by the loop

sync.Pool helps when many goroutines need short-lived buffers, such as a server encoding snapshots for hundreds of clients in parallel. It is a poor fit for game entities. The pool may drop any object during garbage collection, keeping one victim generation so an idle object survives about one extra cycle at most; Get may return a fresh object; and every Get and Put adds ownership rules, which the pool ownership lesson covers. A single-threaded update loop has a simpler, deterministic option: a free list. Keep particles or projectiles in a slice, mark dead ones and push their indexes onto a free list that the next spawn pops. Nothing is allocated once capacity is reached, nothing disappears behind your back, and iterating a dense slice is friendly to the CPU cache.

go
type Particles struct {
	items []Particle
	free  []int // indexes of dead particles, reused before items grows
}

func (p *Particles) Spawn(v Particle) int {
	if n := len(p.free); n > 0 {
		i := p.free[n-1]
		p.free = p.free[:n-1]
		p.items[i] = v
		return i
	}
	p.items = append(p.items, v)
	return len(p.items) - 1
}

func (p *Particles) Kill(i int) {
	p.items[i].Alive = false
	p.free = append(p.free, i)
}
Read the code

This fragment belongs to an update loop in your own game and runs in your native environment; Particle is your struct with an Alive flag that the update skips. Spawn reuses a dead slot before growing items, so once items and free reach their working capacity, spawning and killing allocate nothing. Kill must run once per particle, and other systems that hold an index can see a reused slot; a generation counter per slot, checked on every lookup, catches those stale indexes. Choose sync.Pool when objects cross goroutines and reuse is only an optimization, and a free list when the loop owns them.

05

Turn the measurement into a test and a benchmark

A number printed once is a curiosity; a test that fails when the hot path starts allocating is a guard. Assert exactly zero rather than a non-zero count, because zero stays valid when a Go release changes escape analysis. Pair it with a benchmark that reports time and allocations per update for a scripted scene with a fixed seed, so two runs are comparable.

go
func TestUpdateDoesNotAllocate(t *testing.T) {
	w := NewWorld(500)
	w.Update() // reach steady state: scratch slices at working capacity
	if n := testing.AllocsPerRun(100, w.Update); n != 0 {
		t.Fatalf("Update allocates %v times per call, want 0", n)
	}
}

func BenchmarkUpdate(b *testing.B) {
	w := NewWorld(500)
	b.ReportAllocs()
	for b.Loop() {
		w.Update()
	}
}
Read the code

This fragment goes into a _test.go file beside your World type and runs with go test in your own module. The explicit warm-up call lets scratch slices reach their working capacity before measuring; AllocsPerRun also warms up once on its own. Passing the method value w.Update is fine here because it is created once, outside the measured runs. b.Loop, available since Go 1.24, runs the body the right number of times and keeps the setup above it out of the timing. Run the zero-allocation test without -race and without coverage, since instrumentation can change the counts.

06

Profile the loop you actually ship

When the budget is blown, benchmarks and profiles answer where the time goes and which lines allocate, and traces show whether a slow frame overlapped a GC cycle. Use the same deterministic scene for every comparison.

bash
# Time and allocations per update, five samples for comparison
go test -run '^$' -bench 'Update' -benchmem -count 5 ./game

# CPU and heap profiles from the same benchmark
go test -run '^$' -bench 'Update' -cpuprofile cpu.out -memprofile mem.out ./game
go tool pprof -top cpu.out
go tool pprof -sample_index=alloc_objects -list 'World.Update' mem.out

# GC cycles while the real game runs, one line per cycle on stderr
GODEBUG=gctrace=1 ./mygame 2> gc.log

# Execution trace: GC, goroutines and processor use on one timeline
go test -run '^$' -bench 'Update' -trace trace.out ./game
go tool trace trace.out
Read the code

Run these commands in your own module; ./game and ./mygame stand for your package and binary. -run '^$' skips ordinary tests so only benchmarks run. The heap profile written by -memprofile records allocation sites, and -sample_index=alloc_objects ranks them by count, which matches what AllocsPerRun measures; -list prints source lines with their numbers. gctrace prints one line per GC cycle while the game runs, and the execution trace puts GC, goroutines and processors on one timeline. For spikes that appear only in long sessions, runtime/trace's FlightRecorder keeps the last few seconds in memory, so a debug build can write it to a file when a frame exceeds its budget.

TAKE THIS WITH YOU

Budget each frame from the refresh rate, measure allocations per update with testing.AllocsPerRun, reach zero in steady state by reusing storage the loop owns, and confirm with benchmarks, pprof and traces before tuning the GC.

Check your understanding

What allocation target should a game's per-frame update have, and how do you keep it there?

Go to the source

Progress stays in this browser. No account needed.