Memory, escape analysis, and garbage collection

suggest change

Go manages memory for you: you never call free, and a garbage collector (GC) reclaims memory that is no longer reachable. That doesn't mean memory is free. Every heap allocation costs time to allocate, and it adds work for the GC later.

This article explains where Go puts your values (stack or heap), how to see the compiler's decisions, how the GC works and how to tune it with GOGC and GOMEMLIMIT, and how to measure and reduce allocations.

Stack vs. heap

Each goroutine has its own stack. It starts small (a few KB) and grows as needed. Allocating on the stack is almost free: the compiler reserves space in the function's stack frame, and the space is reclaimed when the function returns. The GC doesn't track stack-allocated values.

The heap is shared by all goroutines. Heap allocations go through the runtime allocator, and the GC must later find and reclaim them.

Go's language spec doesn't say where a variable lives. new(T), &T{} and make don't force a heap allocation, and a local variable isn't guaranteed to be on the stack. The compiler decides, using escape analysis.

Escape analysis

The compiler proves, where it can, that a value is never referenced after the function that created it returns. Such a value can live on the stack. If the compiler can't prove that, the value escapes and is allocated on the heap.

Use -gcflags=-m to see the decisions. Adding -l disables inlining, which makes the output easier to read:

package main

import "fmt"

type Point struct{ X, Y int }

func sum(p Point) int { return p.X + p.Y }

func newPoint(x, y int) *Point {
	p := Point{x, y}
	return &p
}

func fill(n int) []int {
	s := make([]int, n)
	for i := range s {
		s[i] = i
	}
	return s
}

func local() int {
	buf := make([]byte, 64)
	buf[0] = 1
	return int(buf[0])
}

var global *Point

func store(p *Point) { global = p }

func main() {
	a := sum(Point{1, 2})
	p := newPoint(3, 4)
	s := fill(10)
	store(&Point{5, 6})
	fmt.Println(a, p.X, len(s), local())
}
$ go build -gcflags='-m -l' .
./main.go:10:2: moved to heap: p
./main.go:15:11: make([]int, n) escapes to heap
./main.go:23:13: make([]byte, 64) does not escape
./main.go:30:12: leaking param: p
./main.go:36:8: &Point{...} escapes to heap
./main.go:37:13: ... argument does not escape
./main.go:37:14: a escapes to heap
./main.go:37:18: p.X escapes to heap
./main.go:37:25: len(s) escapes to heap
./main.go:37:35: local() escapes to heap

How to read it:

Without -l, newPoint and fill are small enough to be inlined into main. After inlining, the compiler can see that p and the slice don't leave main, and both stay on the stack. Inlining often removes allocations, which is one reason small constructors are cheap.

Use -gcflags='-m=2' for a detailed explanation of why each value escapes. To limit the output to your own package in a larger build, use -gcflags='example.com/mypkg=-m'.

Common reasons a value escapes:

How the garbage collector works

Go uses a concurrent, tri-color, mark-and-sweep collector. It doesn't move objects and has no generations. Most of the marking work runs at the same time as your goroutines. The stop-the-world pauses are usually well under a millisecond.

The cost of GC is roughly proportional to:

Garbage is cheap for the GC; live data and allocation rate are what cost you. Allocating less means fewer GC cycles. A []int or []byte has no pointers, so the GC doesn't need to scan it. A []*T or []string must be scanned.

GOGC

GOGC controls how often the GC runs. After each cycle, the next one is scheduled when the heap has grown by GOGC percent of the live heap (plus GC roots such as goroutine stacks). The default is GOGC=100: with 50 MB of live data, the next cycle starts around 100 MB.

GOMEMLIMIT

GOMEMLIMIT (Go 1.19+) sets a soft limit on the total memory managed by the Go runtime. When memory use approaches the limit, the GC runs more often, regardless of GOGC. Values take a unit suffix: B, KiB, MiB, GiB, TiB.

It is useful in containers with a known memory limit. Set GOMEMLIMIT somewhat below the container limit (for example 90%) to leave room for memory not managed by the Go runtime:

GOMEMLIMIT=900MiB ./server

A common setup for a service that has a dedicated amount of memory is GOGC=off GOMEMLIMIT=...: the GC runs only when the heap approaches the limit. Be careful: if live data is close to the limit, the program will spend most of its time in GC. The runtime caps GC CPU use at about 50% to avoid stalling completely, so in that case memory can exceed the limit.

Both settings can also be changed from code with debug.SetGCPercent and debug.SetMemoryLimit from runtime/debug.

Seeing GC activity

Set GODEBUG=gctrace=1 to print a line to stderr for every GC cycle:

$ GODEBUG=gctrace=1 ./myprog
gc 1 @0.002s 3%: 0+1.1+0 ms clock, 0+0.56/1.6/0+0 ms cpu, 3->4->0 MB, 4 MB goal, 0 MB stacks, 0 MB globals, 14 P

gc 1 is the cycle number, @0.002s is the time since the program started, and 3% is the share of CPU time spent in GC so far. 3->4->0 MB is the heap size at the start of the cycle, at the end of the cycle, and the live heap after marking. 4 MB goal is the target heap size for this cycle.

Measuring memory from code

runtime.ReadMemStats gives a snapshot of allocator and GC statistics. The newer runtime/metrics package exposes the same information and more, with stable names, and it is cheaper to read:

package main

import (
	"fmt"
	"runtime"
	"runtime/debug"
	"runtime/metrics"
)

var sink [][]byte

func printMem(label string) {
	var m runtime.MemStats
	runtime.ReadMemStats(&m)
	fmt.Printf("%-8s heap=%6d KiB  total=%7d KiB  mallocs=%7d  gc=%d\n",
		label, m.HeapAlloc/1024, m.TotalAlloc/1024, m.Mallocs, m.NumGC)
}

func main() {
	printMem("start")

	for i := 0; i < 100_000; i++ {
		b := make([]byte, 1024)
		if i%100 == 0 {
			sink = append(sink, b) // keep 1% alive
		}
	}
	printMem("after")

	runtime.GC()
	printMem("after GC")

	// GOGC and GOMEMLIMIT can also be set from code.
	old := debug.SetGCPercent(200)
	fmt.Println("previous GOGC:", old)
	limit := debug.SetMemoryLimit(-1) // a negative value only reads the limit
	fmt.Println("memory limit:", limit)

	samples := []metrics.Sample{
		{Name: "/gc/heap/allocs:bytes"},
		{Name: "/gc/cycles/total:gc-cycles"},
		{Name: "/memory/classes/heap/objects:bytes"},
	}
	metrics.Read(samples)
	for _, s := range samples {
		fmt.Printf("%s = %d\n", s.Name, s.Value.Uint64())
	}
}

The output looks like this (the numbers vary between runs):

start    heap=   292 KiB  total=    292 KiB  mallocs=    400  gc=0
after    heap=  3753 KiB  total= 100395 KiB  mallocs= 100515  gc=37
after GC heap=  1361 KiB  total= 100400 KiB  mallocs= 100532  gc=39
previous GOGC: 100
memory limit: 9223372036854775807
/gc/heap/allocs:bytes = 102811808
/gc/cycles/total:gc-cycles = 39
/memory/classes/heap/objects:bytes = 1396200

The program allocated about 100 MB in total, but the heap never grew much beyond 4 MB, because the GC ran 37 times during the loop. Run it with GOGC=off and the after line shows the whole 100 MB live, with no GC cycles.

Useful fields:

ReadMemStats briefly stops the world, so don't call it in a hot loop. For heap profiles that show which code allocates, use pprof (see the profiling chapter).

Measuring allocations in benchmarks

The easiest way to find and fix allocations is a benchmark run with -benchmem (or b.ReportAllocs() in the benchmark):

package bench

import (
	"strconv"
	"testing"
)

type Point struct{ X, Y int }

//go:noinline
func newPointPtr(x, y int) *Point { return &Point{x, y} }

//go:noinline
func newPointVal(x, y int) Point { return Point{x, y} }

func BenchmarkPointer(b *testing.B) {
	total := 0
	for b.Loop() {
		p := newPointPtr(1, 2)
		total += p.X
	}
}

func BenchmarkValue(b *testing.B) {
	total := 0
	for b.Loop() {
		p := newPointVal(1, 2)
		total += p.X
	}
}

func joinNaive(nums []int) []byte {
	var out []byte
	for _, n := range nums {
		out = append(out, strconv.Itoa(n)...)
		out = append(out, ',')
	}
	return out
}

// joinAppend appends to dst so the caller can reuse the buffer.
func joinAppend(dst []byte, nums []int) []byte {
	for _, n := range nums {
		dst = strconv.AppendInt(dst, int64(n), 10)
		dst = append(dst, ',')
	}
	return dst
}

var nums = []int{0, 1000, 2000, 3000, 40000, 500000, 6000000}

func BenchmarkJoinNaive(b *testing.B) {
	for b.Loop() {
		_ = joinNaive(nums)
	}
}

func BenchmarkJoinAppend(b *testing.B) {
	buf := make([]byte, 0, 1024)
	for b.Loop() {
		buf = joinAppend(buf[:0], nums)
	}
}

b.Loop() requires Go 1.24 or later. On older versions use for i := 0; i < b.N; i++.

$ go test -bench=. -benchmem
BenchmarkPointer-14      38555331     29.09 ns/op    16 B/op    1 allocs/op
BenchmarkValue-14       553598992      2.054 ns/op     0 B/op    0 allocs/op
BenchmarkJoinNaive-14     1867850    682.8 ns/op     160 B/op   10 allocs/op
BenchmarkJoinAppend-14    4432839    241.2 ns/op       0 B/op    0 allocs/op

//go:noinline stops the compiler from inlining the constructors, so the benchmark shows what happens when a pointer crosses a function boundary: returning *Point costs a heap allocation, while returning Point by value costs nothing. joinNaive allocates for every strconv.Itoa call and every time out grows. joinAppend writes into a buffer the caller owns, and after the first iteration it doesn't allocate at all.

To check that a function doesn't allocate in a test, use testing.AllocsPerRun:

func TestJoinAppendNoAllocs(t *testing.T) {
	buf := make([]byte, 0, 1024)
	allocs := testing.AllocsPerRun(100, func() {
		buf = joinAppend(buf[:0], nums)
	})
	if allocs != 0 {
		t.Fatalf("got %v allocs, want 0", allocs)
	}
}

Techniques for reducing allocations

Measure first. Most code doesn't need this. In hot paths, these help:

After each change, run the benchmark again and compare. golang.org/x/perf/cmd/benchstat shows whether a difference is statistically significant across runs.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents