Go never lets you choose between stack and heap. The compiler makes that call for every variable while it builds the package, and it prints its reasoning if you pass -gcflags=-m. I wrote one small package, game, with a function for each case I wanted to see, then read the compiler output line by line and benchmarked the two cases where the difference shows up in nanoseconds.
Everything below was run with Go 1.27.1 on darwin/arm64 (Apple M4 Max) on November 26, 2026. The callback comparison also uses Go 1.26.0 through GOTOOLCHAIN.
Result first
| Function | What it does | Compiler says (Go 1.27.1) |
|---|---|---|
NewPlayer | builds a Player and returns &p | moved to heap: p |
SpawnPlayer | returns the Player by value | nothing for the player, stays on the stack |
InRange | reads two *Player | a does not escape, b does not escape |
Join | stores the pointer in a package-level map | leaking param: p |
JoinAndLeave | stores it, then deletes it on the next line | leaking param: p |
Connect | passes it to go heartbeat(p) | leaking param: p |
Debug | fmt.Println(&pos) on a local copy | moved to heap: pos |
OnHit | calls one of two handlers that don’t keep the pointer | heap on 1.26.0, stack on 1.27.1 |
OnHitRemember | one possible handler stores the pointer in a global | moved to heap: p on both |
Snapshot / SnapshotBig | make([]byte, 65536) / 65537 | does not escape / escapes to heap |
Frame / FrameBig | var buf [131072]byte / 131073 | stack / moved to heap: buf |
ReadPacket(n) | make([]byte, n) with n known only at run time | does not escape, 0 allocs up to 32 bytes |
| Benchmark (5 runs) | ns/op | B/op | allocs/op |
|---|---|---|---|
NewPlayer | 8.31 – 8.61 | 48 | 1 |
SpawnPlayer | 1.71 – 1.73 | 0 | 0 |
ReadPacket(24) | 1.79 – 1.80 | 0 | 0 |
ReadPacket(32) | 1.79 – 1.80 | 0 | 0 |
ReadPacket(33) | 8.45 – 8.66 | 48 | 1 |
The code
A go.mod with module game and go 1.26, and two files. player.go:
package game
import "fmt"
type Vec struct{ X, Y float64 }
type Player struct {
ID int
Name string
Pos Vec
HP int
}
// NewPlayer creates a player and returns its address.
func NewPlayer(id int, name string) *Player {
p := Player{ID: id, Name: name, HP: 100}
return &p
}
// SpawnPlayer returns the player as a value.
func SpawnPlayer(id int, name string) Player {
return Player{ID: id, Name: name, HP: 100}
}
// InRange only reads through the pointers.
func InRange(a, b *Player, r float64) bool {
dx, dy := a.Pos.X-b.Pos.X, a.Pos.Y-b.Pos.Y
return dx*dx+dy*dy <= r*r
}
var online = map[int]*Player{}
// Join keeps the player in the world after it returns.
func Join(p *Player) {
online[p.ID] = p
}
// JoinAndLeave stores the player and removes it again.
func JoinAndLeave(p *Player) {
online[p.ID] = p
delete(online, p.ID)
}
// Debug prints where the player is.
func Debug(p *Player) {
pos := p.Pos
fmt.Println(&pos)
}
// Connect starts a goroutine for the player.
func Connect(p *Player) {
go heartbeat(p)
}
func heartbeat(p *Player) { _ = p.HP }player.go
tick.go:
package game
// Hit runs the handler it gets on the target.
func Hit(target *Player, handler func(*Player)) {
handler(target)
}
func logHit(p *Player) { _ = p.HP }
func damage(p *Player) { p.HP -= 10 }
var lastHit *Player
func remember(p *Player) { lastHit = p }
// OnHit picks one of two known handlers.
func OnHit(heavy bool) int {
p := Player{HP: 100}
h := logHit
if heavy {
h = damage
}
h(&p)
return p.HP
}
// OnHitRemember picks a handler that may keep the pointer.
func OnHitRemember(keep bool) int {
p := Player{HP: 100}
h := damage
if keep {
h = remember
}
h(&p)
return p.HP
}
// ReadPacket makes a buffer whose size comes from the packet header.
//
//go:noinline
func ReadPacket(n int) int {
buf := make([]byte, n)
buf[0] = 1
return len(buf)
}
// Snapshot keeps a 64 KB buffer for the world state.
func Snapshot() int {
buf := make([]byte, 64<<10)
return len(buf)
}
// SnapshotBig is one byte bigger.
func SnapshotBig() int {
buf := make([]byte, 64<<10+1)
return len(buf)
}
// Frame declares a 128 KB array.
func Frame() int {
var buf [128 << 10]byte
buf[0] = 1
return len(buf)
}
// FrameBig is one byte bigger.
func FrameBig() int {
var buf [128<<10 + 1]byte
buf[0] = 1
return len(buf)
}tick.go
//go:noinline on ReadPacket matters for the benchmark. Without it the call would be inlined into the benchmark loop with a constant size, and the test would no longer measure a size that is unknown at compile time.
The compiler output
go build -gcflags=-m .
The full output, with the can inline lines removed:
./player.go:31:29: map[int]*Player{} escapes to heap
./player.go:15:24: leaking param: name
./player.go:16:2: moved to heap: p
./player.go:21:26: leaking param: name to result ~r0 level=0
./player.go:26:14: a does not escape
./player.go:26:17: b does not escape
./player.go:34:11: leaking param: p
./player.go:39:19: leaking param: p
./player.go:45:12: p does not escape
./player.go:46:2: moved to heap: pos
./player.go:47:13: ... argument does not escape
./player.go:51:14: leaking param: p
./player.go:55:16: p does not escape
./tick.go:4:10: leaking param: target
./tick.go:4:26: handler does not escape
./tick.go:8:13: p does not escape
./tick.go:9:13: p does not escape
./tick.go:13:15: leaking param: p
./tick.go:28:2: moved to heap: p
./tick.go:41:13: make([]byte, n) does not escape
./tick.go:48:13: make([]byte, 65536) does not escape
./tick.go:54:13: make([]byte, 65537) escapes to heap
./tick.go:67:6: moved to heap: bufoutput
There are three kinds of message, and they mean different things:
moved to heap: xis about a local variable. The compiler allocatesxon the heap instead of in the function’s frame. This is the one that costs an allocation.leaking param: pis about a parameter. The function itself allocates nothing, but whatever the caller passes in must already be on the heap, so the cost lands at the call site.x does not escapeis the good case. Formakeit means the backing array fits in the frame.
Note line 21. SpawnPlayer “leaks” name to its result. That only says the string header is copied into the returned value, which is fine: the Player itself is returned by value and nothing is allocated.
Two lines are missing on purpose. OnHit (line 17) has no message on Go 1.27.1, and neither does Frame (line 60). Both stay on the stack.
Why: -m=2
-m=2 prints the data flow behind each decision. For NewPlayer:
go build -gcflags=-m=2 . 2>&1 | grep -A3 "p escapes to heap in NewPlayer"
./player.go:16:2: p escapes to heap in NewPlayer:
./player.go:16:2: flow: ~r0 ← &p:
./player.go:16:2: from &p (address-of) at ./player.go:17:9
./player.go:16:2: from return &p (return) at ./player.go:17:2output
~r0 is the unnamed first result. return &p copies the address into that result, which the caller keeps after the frame is gone.
For Debug, the flow shows where fmt.Println comes in:
./player.go:46:2: pos escapes to heap in Debug:
./player.go:46:2: flow: {storage for ... argument} ← &pos:
./player.go:46:2: from &pos (address-of) at ./player.go:47:14
./player.go:46:2: from &pos (interface-converted) at ./player.go:47:14
./player.go:46:2: from ... argument (slice-literal-element) at ./player.go:47:13
./player.go:46:2: flow: fmt.a ← &{storage for ... argument}:
./player.go:46:2: from ... argument (spill) at ./player.go:47:13output
&pos is converted to an interface{}, put into the variadic ...any slice, and handed to fmt. The slice itself stays on the stack (... argument does not escape), but the pointer inside it goes into code the compiler treats as able to keep it, so pos moves.
Maps, goroutines and “delete right after”
Join, JoinAndLeave and Connect all get leaking param: p. The JoinAndLeave case is the one people get wrong: the pointer is in the map for exactly one statement, yet the result is the same as Join. Escape analysis tracks where a pointer can flow, and storing into a map is a flow to the heap. A later delete does not undo it.
Connect leaks for a similar reason. go heartbeat(p) hands p to a goroutine that can still be running after Connect returns. Note that heartbeat itself gets p does not escape (line 55). The leak comes from the go statement, not from what heartbeat does.
Callbacks: Go 1.26.0 vs Go 1.27.1
GOTOOLCHAIN=go1.26.0 go build -gcflags=-m . 2>&1 | grep "heap: p"
go build -gcflags=-m . 2>&1 | grep "heap: p"
# go1.26.0
./player.go:16:2: moved to heap: p
./tick.go:17:2: moved to heap: p
./tick.go:28:2: moved to heap: p
# go1.27.1
./player.go:16:2: moved to heap: p
./tick.go:28:2: moved to heap: poutput
OnHit (line 17) calls h(&p) where h is either logHit or damage. Neither one keeps the pointer. Go 1.26.0 moves p to the heap anyway; Go 1.27.1 keeps it on the stack. OnHitRemember (line 28) can call remember, which stores the pointer in lastHit, so it goes to the heap on both versions.
Hit, which takes the handler as a parameter, is a different case: leaking param: target on both, because Hit has no idea which function it will be given.
Size limits
| Declaration | Size | Result |
|---|---|---|
make([]byte, 64<<10) | 65,536 B | does not escape |
make([]byte, 64<<10+1) | 65,537 B | escapes to heap |
var buf [128 << 10]byte | 131,072 B | stack (no message) |
var buf [128<<10 + 1]byte | 131,073 B | moved to heap: buf |
So the limit for a constant-size make is 64 KB, and for a declared variable it is 128 KB. Past those, the value goes to the heap even when nothing points at it.
Variable-size make: the 32-byte buffer
ReadPacket takes its size at run time, which used to mean a heap allocation every time. The Go 1.25 release notes say the compiler “can now allocate the backing store for slices on the stack in more situations”. The compiler still reports make([]byte, n) does not escape, but the slice only uses stack memory when n is small enough. The benchmark shows where that stops:
go test -run x -bench . -benchmem -count 5
BenchmarkReadPacket24-16 668303080 1.790 ns/op 0 B/op 0 allocs/op
BenchmarkReadPacket32-16 676286846 1.789 ns/op 0 B/op 0 allocs/op
BenchmarkReadPacket33-16 139374555 8.545 ns/op 48 B/op 1 allocs/opoutput
(One of the five runs each; the table at the top has the ranges.)
The same release notes give a flag that turns these new stack allocations off. With it, even the 24-byte packet allocates:
go test -gcflags=-d=variablemakehash=n -run x -bench ReadPacket24 -benchmem -count 2
BenchmarkReadPacket24-16 179550540 6.662 ns/op 24 B/op 1 allocs/op
BenchmarkReadPacket24-16 182335234 6.531 ns/op 24 B/op 1 allocs/opoutput
At 33 bytes there is one allocation, and it is 48 bytes, not 33. Small heap allocations are rounded up to a fixed size class, and 48 is the class above 32. NewPlayer also shows 48 B: Player is an int, a string header, two float64 and an int, which is 8 + 16 + 16 + 8 = 48 bytes on a 64-bit machine.
Finding the allocations that matter
-gcflags=-m lists every decision in a package, and most of them don’t matter. A heap profile tells you which ones do:
go test -run x -bench 'NewPlayer|ReadPacket33' -benchmem -memprofile mem.out -o game.test
go tool pprof -sample_index=alloc_space -top -nodecount=6 game.test mem.out
flat flat% sum% cum cum%
6.45GB 50.93% 50.93% 6.45GB 50.93% game.ReadPacket
6.21GB 49.05% 100% 6.21GB 49.05% game.NewPlayer (inline)
0 0% 100% 6.21GB 49.05% game.BenchmarkNewPlayer
0 0% 100% 6.45GB 50.93% game.BenchmarkReadPacket33output
The order that works: profile to find the functions that allocate the most, then run go build -gcflags=-m on that package and search for those line numbers to see why. -sample_index=alloc_space counts everything allocated during the run. With -sample_index=inuse_space, which counts only what was still alive when the profile was written, the same file shows 2,562 kB in total: values like these die right after the call, so look at allocations, not at what is in use.
A returned pointer is not a bug. NewPlayer costs about 7 ns more than SpawnPlayer per call, which matters in a loop that runs for every player on every tick and does not matter in setup code that runs once.
Repeat it
mkdir game && cd game
go mod init game # the runs above used "go 1.26" in go.mod
# add player.go, tick.go and arena_test.go from above
go build -gcflags=-m .
go build -gcflags=-m=2 .
go test -run x -bench . -benchmem -count 5
GOTOOLCHAIN=go1.26.0 go build -gcflags=-m .
arena_test.go, the benchmarks. The package-level sink variables keep the compiler from deleting the calls:
package game
import "testing"
var sinkP *Player
var sinkV Player
var sinkN int
func BenchmarkNewPlayer(b *testing.B) {
for b.Loop() {
sinkP = NewPlayer(7, "neo")
}
}
func BenchmarkSpawnPlayer(b *testing.B) {
for b.Loop() {
sinkV = SpawnPlayer(7, "neo")
}
}
func BenchmarkReadPacket24(b *testing.B) {
for b.Loop() {
sinkN = ReadPacket(24)
}
}
func BenchmarkReadPacket32(b *testing.B) {
for b.Loop() {
sinkN = ReadPacket(32)
}
}
func BenchmarkReadPacket33(b *testing.B) {
for b.Loop() {
sinkN = ReadPacket(33)
}
}arena_test.go
Numbers in nanoseconds will differ on your machine. The compiler messages, the allocation counts and the 48-byte size class should not, as long as you use the same Go versions.