← Writing

The Compiler Decides What Escapes

Contents

Add one fmt.Println to a Go function that never allocated, and every call to it now allocates. Nothing in the source says where a variable lives. Go has no new that means “heap” and no declaration that means “stack”. The compiler decides, one variable at a time, by working out whether anything could still refer to the variable after its function returns. If something could, the variable escapes and goes on the heap. If nothing could, it stays in the stack frame and costs nothing to free. The debugging line made a variable escape, and the compiler moved it without saying a word.

This post is about that decision, which compilers call escape analysis. It shows how to make the Go compiler explain its choices, works through fourteen small cases with what each one costs, finds the size limits beyond which nothing stays on the stack, and shows how inlining can change a verdict without a line of the function changing. It then looks at four other languages, which make the same decision in four different places: Java at run time in its JIT compiler, C# and Rust in the programmer’s hands, and C++ mostly by hand but sometimes, it turns out, in the optimiser.

This is Part 2 of a series on how Go manages the stack and the heap. Part 1 showed how goroutine stacks grow and move; this part is about what gets to live on them. It is written for Go programmers who have used go test -bench. Everything here ran on Go 1.10.3, released on 5 June, on an Ubuntu 18.04 userland, with OpenJDK 8, .NET Core 2.1, gcc 7.3, clang 6.0 and Rust 1.26.2 for the comparisons. The note at the end says what was measured and how.

Why it matters where a variable lives

Part 1 showed what a stack frame costs: moving the stack pointer down on entry and back up on exit. Everything in the frame is freed at once, for free, when the function returns. The heap is the opposite. Allocating there means finding a free block of the right size, and freeing it is the garbage collector’s job: it has to find out, later, that nothing points to the block any more. A small heap allocation in Go costs several nanoseconds at the moment it is made (about 7 for the 16-byte one measured below, and more for larger ones) and more again when the collector deals with it. The more a program allocates, the more often the collector runs.

So the cheapest object is one that is never on the heap at all. In C the programmer chooses: a local variable is on the stack, malloc is the heap, and returning a pointer to a local is a bug the compiler may or may not warn about. Go removes that bug by construction. You may return a pointer to a local variable, and the program is correct:

func newPoint() *point {
	p := point{1, 2}
	return &p // fine in Go: p outlives the call
}

For that to be correct, p cannot be in newPoint’s frame, because the frame is gone when the function returns. The compiler sees the &p that leaves the function and puts p on the heap instead. The Go FAQ is explicit that this is the compiler’s business:

How do I know whether a variable is allocated on the heap or the stack?

From a correctness standpoint, you don’t need to know. Each variable in Go exists as long as there are references to it. The storage location chosen by the implementation is irrelevant to the semantics of the language.

The storage location does have an effect on writing efficient programs.

That is true for correctness and false for speed. The rest of this post is about the speed.

Escape analysis

This section explains the analysis itself. If you only want to see what it decides, skip to the next one.

A variable escapes if a pointer to it may still exist after the function that declared it has returned. The compiler cannot run the program to find out, so it reasons about every place a pointer could go. In Go 1.10 the pass lives in src/cmd/compile/internal/gc/esc.go, and it works like this:

  1. It builds a graph of the function. The nodes are variables, and the edges say “the value of this flows into that”: an assignment, a function argument, a return value, a field of a struct, an element stored in a slice, a variable captured by a closure.
  2. A few places are sinks that the analysis treats as “lives forever”: global variables, the heap itself, and anything it cannot see into. A value stored into a global escapes. A pointer passed to a function through an interface escapes, because the compiler does not know which function will run.
  3. A variable whose address can reach a sink, by any path through the graph, escapes. Everything else stays in the frame.
  4. Each function also gets a summary of what it does with its parameters. “leaking param: w” means the function may store w somewhere that outlives the call. A caller uses these summaries instead of re-analysing the callee, so the analysis works function by function, in the order of the call graph.

Two properties of the analysis drive everything below. First, it is conservative: when it cannot prove a pointer stays local, it assumes the pointer escapes. A wrong “stays” would leave a pointer into a stack frame that no longer exists, which is memory corruption, while a wrong “escapes” only costs an allocation. Second, it is static: it decides at compile time, once, for every possible execution. A pointer that escapes on one rare path makes the variable escape on every path.

Escape analysis was not invented for Go. The idea goes back to work on Lisp and functional languages in the 1980s and 1990s, and Java made it famous: “Escape Analysis for Java”, by Jong-Deok Choi and colleagues at IBM (OOPSLA 1999), used it both to put objects on the stack and to remove locks that only one thread could ever take. Go’s compiler has had it since August 2011, before Go 1.0, when Luuk van Dijk added it in a commit titled simply “gc: Escape analysis.” What is unusual about Go is not the analysis but the language around it. Go lets the programmer take the address of any variable, so the analysis decides the fate of ordinary local variables, not only of objects created with new.

Asking the compiler

The compiler reports its decisions when it is built with -gcflags=-m. A second -m explains each one. Here is a file of small functions, each a case worth knowing about:

package esc

import (
	"bytes"
	"fmt"
	"io"
)

type point struct{ x, y int }

// 1. Returned by value: the caller gets a copy, nothing outlives the frame.
//go:noinline
func byValue(x, y int) point { return point{x, y} }

// 2. Returned by pointer: the point must outlive the frame.
//go:noinline
func byPointer(x, y int) *point { return &point{x, y} }

// 3. The same function, but small enough to inline (no //go:noinline).
func byPointerInl(x, y int) *point { return &point{x, y} }

// 4. A debugging line added to an otherwise allocation-free function.
func sumQuiet(p point) int { return p.x + p.y }

func sumLoud(p point) int {
	s := p.x + p.y
	fmt.Println("sum", s)
	return s
}

// 5. Slices: constant small size, constant size at the limit, a variable size.
func makeConst() byte {
	b := make([]byte, 64)
	b[3] = 1
	return b[3]
}

func makeLimitBelow() byte {
	b := make([]byte, 65535)
	b[3] = 1
	return b[3]
}

func makeLimit() byte {
	b := make([]byte, 65536)
	b[3] = 1
	return b[3]
}

func makeVar(n int) byte {
	b := make([]byte, n)
	b[3] = 1
	return b[3]
}

// 6. Closures: called in place, or handed to a function that keeps it.
var kept func() int

func closureLocal() int {
	n := 1
	f := func() int { n++; return n }
	return f()
}

func closureKept() int {
	n := 1
	kept = func() int { n++; return n }
	return kept()
}

// 7. An interface call the compiler cannot see through.
func viaInterface(w io.Writer) {
	var buf [16]byte
	w.Write(buf[:])
}

func viaConcrete(w *bytes.Buffer) {
	var buf [16]byte
	w.Write(buf[:])
}

// 8. A value stored in an interface.
type shape interface{ area() int }
type square struct{ s int }

func (q square) area() int { return q.s * q.s }

var sink shape

func toInterface(s int) {
	sink = square{s}
}

And a benchmark for each, so that every verdict comes with its price. testing.B reports bytes and allocations per operation with -benchmem:

package esc

import (
	"bytes"
	"io/ioutil"
	"os"
	"testing"
)

var gp *point
var gi int
var gb byte

func BenchmarkByValue(b *testing.B) {
	for i := 0; i < b.N; i++ {
		p := byValue(i, i)
		gi += p.x
	}
}

func BenchmarkByPointer(b *testing.B) {
	for i := 0; i < b.N; i++ {
		p := byPointer(i, i)
		gi += p.x
	}
}

func BenchmarkByPointerInlined(b *testing.B) {
	for i := 0; i < b.N; i++ {
		p := byPointerInl(i, i)
		gi += p.x
	}
}

func BenchmarkSumQuiet(b *testing.B) {
	for i := 0; i < b.N; i++ {
		gi += sumQuiet(point{i, i})
	}
}

func BenchmarkSumLoud(b *testing.B) {
	stdout := os.Stdout
	os.Stdout, _ = os.OpenFile(os.DevNull, os.O_WRONLY, 0)
	defer func() { os.Stdout = stdout }()
	for i := 0; i < b.N; i++ {
		gi += sumLoud(point{i, i})
	}
}

func BenchmarkMakeConst64(b *testing.B) {
	for i := 0; i < b.N; i++ {
		gb += makeConst()
	}
}

func BenchmarkMakeConst65535(b *testing.B) {
	for i := 0; i < b.N; i++ {
		gb += makeLimitBelow()
	}
}

func BenchmarkMakeConst65536(b *testing.B) {
	for i := 0; i < b.N; i++ {
		gb += makeLimit()
	}
}

func BenchmarkMakeVar64(b *testing.B) {
	for i := 0; i < b.N; i++ {
		gb += makeVar(64)
	}
}

func BenchmarkClosureLocal(b *testing.B) {
	for i := 0; i < b.N; i++ {
		gi += closureLocal()
	}
}

func BenchmarkClosureKept(b *testing.B) {
	for i := 0; i < b.N; i++ {
		gi += closureKept()
	}
}

func BenchmarkViaInterface(b *testing.B) {
	var w bytes.Buffer
	for i := 0; i < b.N; i++ {
		w.Reset()
		viaInterface(&w)
	}
}

func BenchmarkViaConcrete(b *testing.B) {
	var w bytes.Buffer
	for i := 0; i < b.N; i++ {
		w.Reset()
		viaConcrete(&w)
	}
}

func BenchmarkToInterface(b *testing.B) {
	for i := 0; i < b.N; i++ {
		toInterface(i)
	}
}

var _ = ioutil.Discard

The compiler’s verdicts, with -m:

$ go build -gcflags=-m esc.go
# command-line-arguments
./esc.go:20:6: can inline byPointerInl
./esc.go:23:6: can inline sumQuiet
./esc.go:32:6: can inline makeConst
./esc.go:38:6: can inline makeLimitBelow
./esc.go:44:6: can inline makeLimit
./esc.go:50:6: can inline makeVar
./esc.go:61:7: can inline closureLocal.func1
./esc.go:62:10: inlining call to closureLocal.func1
./esc.go:67:9: can inline closureKept.func1
./esc.go:86:6: can inline square.area
./esc.go:90:6: can inline toInterface
./esc.go:17:52: &point literal escapes to heap
./esc.go:20:55: &point literal escapes to heap
./esc.go:27:14: "sum" escapes to heap
./esc.go:27:14: s escapes to heap
./esc.go:27:13: sumLoud ... argument does not escape
./esc.go:33:11: makeConst make([]byte, 64) does not escape
./esc.go:39:11: makeLimitBelow make([]byte, 65535) does not escape
./esc.go:45:11: make([]byte, 65536) escapes to heap
./esc.go:51:11: make([]byte, n) escapes to heap
./esc.go:61:7: closureLocal func literal does not escape
./esc.go:62:10: closureLocal &n does not escape
./esc.go:67:9: func literal escapes to heap
./esc.go:67:9: func literal escapes to heap
./esc.go:67:22: &n escapes to heap
./esc.go:66:2: moved to heap: n
./esc.go:74:13: buf escapes to heap
./esc.go:73:6: moved to heap: buf
./esc.go:72:21: leaking param: w
./esc.go:77:21: leaking param: w
./esc.go:79:13: viaConcrete buf does not escape
./esc.go:91:7: square literal escapes to heap
<autogenerated>:1:0: leaking param: .this
<autogenerated>:1:0: inlining call to square.area
<autogenerated>:1:0: (*square).area .this does not escape

And their prices, as the median of five runs of each benchmark in one sitting (go test -bench . -benchmem -count 5):

Casens/opB/opallocs/op
1. byValue1.2200
2. byPointer8.45161
3. byPointerInl1.4600
4. sumQuiet1.4500
4. sumLoud22581
5. make([]byte, 64)1.2200
5. make([]byte, 65535)59700
5. make([]byte, 65536)4,10865,5361
5. make([]byte, n), n = 6413.1641
6. closureLocal1.2400
6. closureKept16.2242
7. viaInterface9.96161
7. viaConcrete2.9200
8. toInterface6.3080 (really 1: see below)

Where each value lived, and what it cost

Nanoseconds per operation (log scale), median of 5 runs, Go 1.10.3.

stayed on the stackmoved to the heap
ByValuestack 1.22
ByPointerheap 8.45
ByPointerInlinedstack 1.46
SumQuietstack 1.45
SumLoudheap 225
MakeConst64stack 1.22
MakeConst65535stack 597
MakeConst65536heap 4,108
MakeVar64heap 13.1
ClosureLocalstack 1.24
ClosureKeptheap 16.2
ViaInterfaceheap 9.96
ViaConcretestack 2.92
ToInterfaceheap 6.30

Hover or focus a row to see its code and the compiler's reason.

The rest of this section takes the cases in order.

Returning a pointer

byValue returns a point by value. The 16 bytes are copied into the caller’s frame, and nothing is allocated. byPointer returns &point{x, y}, and the compiler says &point literal escapes to heap. With -m -m it says why:

./esc.go:17:52: &point literal escapes to heap
./esc.go:17:52: 	from ~r2 (return) at ./esc.go:17:35

~r2 is the compiler’s name for the function’s unnamed result. The point flows into the result, the result leaves the function, and so the point must outlive the frame. It costs one 16-byte allocation and makes the call seven times slower: 8.45 ns against 1.22.

Returning a small struct by value is not the wasteful choice it looks like to a C programmer. For anything up to a few words, copying it is cheaper than allocating it.

What an escape looks like in the machine code

The verdict is not only a message. It changes the code the compiler emits, and the disassembly of the test binary shows the difference. byValue is four moves and a return. It reads x and y from its arguments and writes them into its result slots, which are in the caller’s frame:

$ go test -c -o esc.test && go tool objdump -s 'esc\.byValue$' esc.test
TEXT _/tmp/p6/esc.byValue(SB) /tmp/p6/esc/esc.go
  esc.go:13		0x4e5de0		488b442408		MOVQ 0x8(SP), AX
  esc.go:13		0x4e5de5		4889442418		MOVQ AX, 0x18(SP)
  esc.go:13		0x4e5dea		488b442410		MOVQ 0x10(SP), AX
  esc.go:13		0x4e5def		4889442420		MOVQ AX, 0x20(SP)
  esc.go:13		0x4e5df4		c3			RET

It has no stack check either: it calls nothing and has no frame of its own, so it is one of the NOSPLIT leaves from Part 1. byPointer is a different function:

$ go tool objdump -s 'esc\.byPointer$' esc.test
TEXT _/tmp/p6/esc.byPointer(SB) /tmp/p6/esc/esc.go
  esc.go:17		0x4e5e00		64488b0c25f8ffffff	MOVQ FS:0xfffffff8, CX
  esc.go:17		0x4e5e09		483b6110		CMPQ 0x10(CX), SP
  esc.go:17		0x4e5e0d		7643			JBE 0x4e5e52
  esc.go:17		0x4e5e0f		4883ec18		SUBQ $0x18, SP
  esc.go:17		0x4e5e13		48896c2410		MOVQ BP, 0x10(SP)
  esc.go:17		0x4e5e18		488d6c2410		LEAQ 0x10(SP), BP
  esc.go:17		0x4e5e1d		488d057c8f0200		LEAQ 0x28f7c(IP), AX
  esc.go:17		0x4e5e24		48890424		MOVQ AX, 0(SP)
  esc.go:17		0x4e5e28		e84393f2ff		CALL runtime.newobject(SB)
  esc.go:17		0x4e5e2d		488b442408		MOVQ 0x8(SP), AX
  esc.go:17		0x4e5e32		488b4c2420		MOVQ 0x20(SP), CX
  esc.go:17		0x4e5e37		488908			MOVQ CX, 0(AX)
  esc.go:17		0x4e5e3a		488b4c2428		MOVQ 0x28(SP), CX
  esc.go:17		0x4e5e3f		48894808		MOVQ CX, 0x8(AX)
  esc.go:17		0x4e5e43		4889442430		MOVQ AX, 0x30(SP)
  esc.go:17		0x4e5e48		488b6c2410		MOVQ 0x10(SP), BP
  esc.go:17		0x4e5e4d		4883c418		ADDQ $0x18, SP
  esc.go:17		0x4e5e51		c3			RET
  esc.go:17		0x4e5e52		e889c5f6ff		CALL runtime.morestack_noctxt(SB)
  esc.go:17		0x4e5e57		eba7			JMP _/tmp/p6/esc.byPointer(SB)

Now there is a frame, a stack check, and a call. LEAQ 0x28f7c(IP), AX loads the address of the type descriptor for point, and CALL runtime.newobject asks the allocator for a zeroed object of that type. The two MOVQ CX, ...(AX) instructions then write x and y through the pointer that came back, and the pointer is the result. runtime.newobject is a thin wrapper around mallocgc, the allocator’s entry point: every escaping variable in a Go program ends in a call like this one.

The benchmark that calls the inlinable byPointerInl (the next case) has no CALL instruction in its loop at all. go tool objdump -s 'esc\.BenchmarkByPointerInlined$' esc.test | grep CALL prints nothing: no call to the function, which was inlined, and no call to runtime.newobject, because the point no longer escapes.

Inlining changes the answer

byPointerInl is the same function without //go:noinline. The compiler reports the same verdict for the function itself, &point literal escapes to heap, yet the benchmark shows no allocation at all: 1.46 ns, 0 B/op. Both are right.

The verdict on line 20 is about byPointerInl compiled as a function in its own right, the copy other packages would call. But the compiler also inlined it into BenchmarkByPointerInlined: it copied the function’s body into the loop, so there was no call. Once the body is in the loop, the &point{...} is a local of the benchmark function, and the analysis runs again there. The pointer goes into p, p.x is read, and p is never stored anywhere, so the point does not escape the loop body and goes on the stack.

This is the most important thing to understand about escape analysis in Go 1.10: a pointer returned out of a function escapes, unless the inliner removes the function. And the inliner is choosy. It only inlines a function whose body is below a budget (80 nodes of the compiler’s syntax tree in 1.10), and it refuses some kinds of statement outright. -m -m shows its reasons:

./esc.go:20:6: can inline byPointerInl as: func(int, int) *point { return &point literal }
./esc.go:25:6: cannot inline sumLoud: non-leaf function
./esc.go:59:6: cannot inline closureLocal: unhandled op CLOSURE
./esc.go:72:6: cannot inline viaInterface: non-leaf op CALLINTER

sumLoud cannot be inlined because it calls another function, fmt.Println. In Go 1.10, a function that calls anything that is not itself inlined is not inlined. Add a line to a small constructor that calls a logger, a validator or a metrics counter, and the constructor stops being inlined. Every caller that used to get its result on the stack now gets it from the heap. The constructor’s own code has not become any slower. The calls to it have.

The debugging line

sumQuiet adds two fields and costs 1.45 ns. sumLoud does the same and prints the result. It costs 225 ns, spent formatting the line and making the write system call to /dev/null, and it allocates 8 bytes on every call. The compiler explains:

./esc.go:27:14: s escapes to heap
./esc.go:27:14: 	from ... argument (arg to ...) at ./esc.go:27:13
./esc.go:27:14: 	from *(... argument) (indirection) at ./esc.go:27:13
./esc.go:27:14: 	from ... argument (passed to call[argument content escapes]) at ./esc.go:27:13

fmt.Println takes ...interface{}. To put the integer s into an interface{}, the compiler has to make an interface value: a pointer to the type and a pointer to the data. The data is a copy of s somewhere in memory. Where? fmt.Println hands its arguments to code that the analysis of fmt marked as “argument content escapes” (they can end up in the printer’s internal state, and through reflection, anywhere), so the copy of s must be on the heap. That is the 8 bytes.

-m also says "sum" escapes to heap, yet there is only one allocation. The difference is that "sum" is a constant. The compiler can build the interface value’s data for a constant string once, in the program’s read-only data, so “escaping” costs nothing at run time. s changes on every call, so its copy has to be made on every call.

The leak is the size of the change compared with its cause. One line, added to investigate something, puts an allocation on a path that had none. The same goes for a logger that takes ...interface{} and checks its level inside the call: the value is boxed into an interface by the caller, before the check, so the allocation happens even when nothing is printed.

Size

The analysis has a second rule that has nothing to do with pointers: big things go on the heap whether they escape or not. From esc.go:

	// Big stuff escapes unconditionally
	// "Big" conditions that were scattered around in walk have been gathered here
	if n.Esc != EscHeap && n.Type != nil &&
		(n.Type.Width > maxStackVarSize ||
			(n.Op == ONEW || n.Op == OPTRLIT) && n.Type.Elem().Width >= 1<<16 ||
			n.Op == OMAKESLICE && !isSmallMakeSlice(n)) {
		if Debug['m'] > 2 {
			Warnl(n.Pos, "%v is too large for stack", n)
		}
		n.Esc = EscHeap
		addrescapes(n)
		e.escassignSinkWhy(n, n, "too large for stack") // TODO category: tooLarge
	}

with maxStackVarSize = 10 * 1024 * 1024 in go.go and, in walk.go:

	return smallintconst(l) && smallintconst(r) && (t.Elem().Width == 0 || r.Int64() < (1<<16)/t.Elem().Width)

So in Go 1.10:

  • a declared variable larger than 10 MB goes on the heap;
  • new(T) or &T{...} of 64 KB or more goes on the heap;
  • make([]T, n) goes on the heap unless n is a constant and the slice is under 64 KB.

The benchmarks sit on either side of the line. make([]byte, 65535) stays on the stack, and make([]byte, 65536) does not. The variable-size case is the one that matters in real code: make([]byte, n) with n = 64 allocates, at 13.1 ns, where the same 64 bytes with a constant length cost nothing. The compiler has to know the size of a frame when it compiles the function, so a slice whose length is only known at run time cannot be in it. Go has no alloca.

The 65,535-byte case shows that the stack is not free either. It costs 597 ns per call with no allocation. Go zeroes every variable, so each call has to clear 64 KB of stack, and that is most likely where the time goes (I did not profile it). The heap version costs 4,108 ns: the allocator has to find 64 KB and zero it, and the collector has more to do.

How big may a value be and stay on the stack?

Go 1.10, by how the value is made. Size axis doubles at each step, 1 B to 64 MB.

stack, if it does not escapeheap, always
declared variablevar a [N]byte
stack, up to 10 MBheap

Measured: 9 MB stayed on the stack, and the goroutine stack grew by 16 MB to hold it; 11 MB went to the heap.

new or composite literal&T{...}
stack, under 64 KBheap
make, constant lengthmake([]byte, 64)
stack, under 64 KBheap

Measured: 64 B 1.22 ns and 65,535 B 597 ns on the stack (the cost is zeroing it); 65,536 B 4,108 ns on the heap.

make, length known only at run timemake([]byte, n)
heap, at any size

Measured: n = 64 on the heap, 13.1 ns and one 64-byte allocation.

Under the 10 MB rule there is a stranger consequence of Part 1. A 9 MB array is a local variable like any other, so it goes in the frame, and the frame goes on a goroutine stack that started at 2 KB:

package main

import (
	"fmt"
	"runtime"
)

// 9 MB: under the compiler's 10 MB limit, so it is a local on the stack.
//go:noinline
func nineMB() byte {
	var a [9 << 20]byte
	a[12345] = 1
	return a[12345]
}

// 11 MB: over the limit, so the compiler puts it on the heap.
//go:noinline
func elevenMB() byte {
	var a [11 << 20]byte
	a[12345] = 1
	return a[12345]
}

func measure(name string, f func() byte) {
	var before, after runtime.MemStats
	runtime.ReadMemStats(&before)
	done := make(chan runtime.MemStats)
	go func() {
		f()
		var during runtime.MemStats
		runtime.ReadMemStats(&during) // still on the goroutine that called f
		done <- during
	}()
	during := <-done
	runtime.ReadMemStats(&after)
	fmt.Printf("%-9s StackInuse +%6d KB   HeapAlloc +%6d KB   Mallocs +%d\n", name,
		(during.StackInuse-before.StackInuse)>>10, (during.HeapAlloc-before.HeapAlloc)>>10, during.Mallocs-before.Mallocs)
}

func main() {
	measure("nineMB", nineMB)
	measure("elevenMB", elevenMB)
}
$ go build -gcflags=-m bigarr.go 2>&1 | grep 'moved to heap'
./bigarr.go:19:6: moved to heap: a
$ go build bigarr.go && ./bigarr
nineMB    StackInuse + 16416 KB   HeapAlloc +     2 KB   Mallocs +6
elevenMB  StackInuse +   224 KB   HeapAlloc + 11275 KB   Mallocs +62

Only the 11 MB array (line 19) is moved to the heap. The 9 MB one stays in its frame, and to make room for it the goroutine’s stack grew to 16 MB, by doubling and copying as in Part 1. Past the 10 MB line, the same code costs a heap allocation instead of a stack growth.

Closures

A closure that captures a variable by reference needs the variable to live as long as the closure does. If the closure is called on the spot, as in closureLocal, neither the closure nor n escapes: the compiler even inlines the closure’s body (inlining call to closureLocal.func1), and the call costs 1.24 ns. If the closure is stored in a global, as in closureKept, both escape:

./esc.go:67:22: &n escapes to heap
./esc.go:67:22: 	from func literal (captured by a closure) at ./esc.go:67:9
./esc.go:67:22: 	from &(func literal) (address-of) at ./esc.go:67:9
./esc.go:67:22: 	from kept (assigned to top level variable) at ./esc.go:57:5
./esc.go:66:2: moved to heap: n

That is two allocations, 24 bytes: 8 for n and 16 for the closure itself, which holds a pointer to its code and a pointer to n. The same applies to a closure passed to go, which starts a new goroutine whose stack is unrelated to this one, and to any callback registered somewhere that keeps it.

Interfaces: the wall the analysis cannot see through

viaInterface and viaConcrete do the same thing: make a 16-byte array and pass a slice of it to Write. One takes an io.Writer, the other a *bytes.Buffer. The concrete one keeps buf on the stack. The interface one moves it to the heap:

./esc.go:74:13: buf escapes to heap
./esc.go:74:13: 	from w.Write(buf[:]) (parameter to indirect call) at ./esc.go:74:9
./esc.go:73:6: moved to heap: buf

“Indirect call” is the key. A call through an interface is a jump through a table of function pointers, and at compile time the compiler does not know which Write will run. It might be one that keeps the slice. So the analysis has to assume it does. With the concrete type, it can look at bytes.Buffer.Write’s summary, which says the slice’s contents are copied and the slice itself is not kept. The price here is one 16-byte allocation and 7 ns per call.

It is also one reason the standard library’s I/O interfaces take memory instead of returning it. io.Reader.Read(p []byte) fills a buffer the caller provides, so a caller can allocate one buffer and reuse it for every read. The caller’s buffer still escapes, because it is passed through an interface, but it does so once, not on every call.

A value in an interface

toInterface stores a square into an interface-typed global. The square escapes (it is reachable from a global), so its 8 bytes must be copied to the heap. The benchmark reports 8 B/op and, in four of its five runs, 0 allocs/op, which looks impossible. The zero is arithmetic. testing computes the figure as int64(r.MemAllocs) / int64(r.N), an integer division, so a count just under one allocation per operation prints as 0 (the fifth run came out just over, and printed 1). Counting directly, around a thousand calls, shows the allocation is there:

package main

import (
	"fmt"
	"os"
	"runtime"
)

type square struct{ s int }

var sinkE interface{}
var sinkS fmt.Stringer
var shape interface{ area() int }

func (q square) area() int { return q.s * q.s }

func count(name string, f func(i int)) {
	var a, b runtime.MemStats
	runtime.GC()
	runtime.ReadMemStats(&a)
	for i := 0; i < 1000; i++ {
		f(i)
	}
	runtime.ReadMemStats(&b)
	fmt.Fprintf(os.Stderr, "%-28s mallocs/op %.3f  bytes/op %.1f\n", name,
		float64(b.Mallocs-a.Mallocs)/1000, float64(b.TotalAlloc-a.TotalAlloc)/1000)
}

func main() {
	null, _ := os.OpenFile(os.DevNull, os.O_WRONLY, 0)
	os.Stdout = null
	count("int into interface{}", func(i int) { sinkE = i })
	count("square into interface", func(i int) { shape = square{i} })
	count("fmt.Println(\"sum\", i)", func(i int) { fmt.Println("sum", i) })
	count("fmt.Fprintln(null, i)", func(i int) { fmt.Fprintln(null, i) })
}
$ go run box.go
int into interface{}         mallocs/op 1.002  bytes/op 9.8
square into interface        mallocs/op 1.002  bytes/op 9.8
fmt.Println("sum", i)        mallocs/op 1.006  bytes/op 13.1
fmt.Fprintln(null, i)        mallocs/op 1.007  bytes/op 13.1

One allocation per call, as for the boxed s in sumLoud. The bytes are the odd part: about 10 per call rather than 16, and the benchmark’s 8 B/op says the same. Go’s allocator has a special path for objects under 16 bytes that contain no pointers. It packs them into shared 16-byte blocks, so two 8-byte squares take one block between them. Each still counts as an allocation; only the memory is shared. How the allocator does that, and what it costs, is a story for another post.

Java decides at run time

Java has no way to put an object on the stack. new always means the heap, as far as the language is concerned. But HotSpot, the JVM in OpenJDK, runs escape analysis inside its optimising JIT compiler, and has done so by default since Java 6 Update 23. When it proves an object does not escape a compiled method, it removes the allocation. HotSpot does not move the object onto the stack; it replaces it with its fields, kept in registers or stack slots like any local variable. This is called scalar replacement.

The same two cases as byValue/byPointer, in Java 8, measured with the JVM’s per-thread count of allocated bytes:

import java.lang.management.ManagementFactory;

public class EA {
    static final class Point {
        final long x, y;
        Point(long x, long y) { this.x = x; this.y = y; }
    }

    static Point keep;

    // The Point never leaves the loop body.
    static long local(long n) {
        long s = 0;
        for (long i = 0; i < n; i++) {
            Point p = new Point(i, i + 1);
            s += p.x + p.y;
        }
        return s;
    }

    // The Point is stored where other code can see it.
    static long kept(long n) {
        long s = 0;
        for (long i = 0; i < n; i++) {
            Point p = new Point(i, i + 1);
            keep = p;
            s += p.x + p.y;
        }
        return s;
    }

    interface Body { long run(long n); }

    static void measure(String name, Body b) {
        com.sun.management.ThreadMXBean mx =
            (com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean();
        long id = Thread.currentThread().getId();
        final long n = 50_000_000L;
        long sink = 0;
        for (int w = 0; w < 10; w++) sink += b.run(n); // let the JIT compile it
        long a0 = mx.getThreadAllocatedBytes(id), t0 = System.nanoTime();
        sink += b.run(n);
        long t1 = System.nanoTime(), a1 = mx.getThreadAllocatedBytes(id);
        System.out.printf("%-6s %6.2f ns/iter  %6.2f bytes allocated/iter  (%d)%n",
            name, (t1 - t0) / (double) n, (a1 - a0) / (double) n, sink & 1);
    }

    public static void main(String[] args) {
        measure("local", EA::local);
        measure("kept", EA::kept);
    }
}
$ javac EA.java && java EA && java -XX:-DoEscapeAnalysis EA
local    0.24 ns/iter    0.00 bytes allocated/iter  (0)
kept     3.38 ns/iter   32.00 bytes allocated/iter  (0)
local    2.94 ns/iter   32.00 bytes allocated/iter  (0)
kept     3.52 ns/iter   32.00 bytes allocated/iter  (0)

(The first two lines are the default JVM, the last two with escape analysis switched off.) With it on, the Point that stays local costs nothing at all: no bytes allocated, and a quarter of a nanosecond per iteration, which is just the arithmetic. The stored one costs 32 bytes per iteration: 16 for the two fields, 12 for the header every Java object carries (with the JVM’s default compressed class pointers), and 4 of padding to an 8-byte boundary. With escape analysis off, the local one allocates exactly as much as the stored one.

The difference from Go is when the decision is made. HotSpot decides at run time, after it has inlined whatever the profile says is hot, and it can inline through an interface call if only one implementation has been seen so far (and undo it if another one appears later). So it can sometimes prove more than Go’s compiler can. But the decision is invisible: no -m tells you what it decided (there are diagnostic flags, in debug builds of the JVM), and the same code can allocate in one run and not in another, depending on what got compiled and inlined. Go’s decision is made once, at build time, and can be printed.

C# lets you choose

C# has the choice built into its types. A struct is a value type: a local of struct type lives in the frame, and assigning it copies it. A class is a reference type: new always allocates on the heap. The same point, both ways, on .NET Core 2.1, released at the end of May, counting how many times the garbage collector had to run:

using System;

struct PointS { public long X, Y; public PointS(long x, long y) { X = x; Y = y; } }
class PointC { public long X, Y; public PointC(long x, long y) { X = x; Y = y; } }

static class Program
{
    static long WithStruct(long n) { long s = 0; for (long i = 0; i < n; i++) { var p = new PointS(i, i + 1); s += p.X + p.Y; } return s; }
    static long WithClass(long n)  { long s = 0; for (long i = 0; i < n; i++) { var p = new PointC(i, i + 1); s += p.X + p.Y; } return s; }

    // stackalloc outside the loop: one 64-byte buffer for the whole call.
    static long WithStackalloc(long n)
    {
        long s = 0;
        Span<long> buf = stackalloc long[8]; // C# 7.2: no unsafe needed with Span<T>
        for (long i = 0; i < n; i++)
        {
            buf[(int)(i & 7)] = i;
            s += buf[(int)(i & 7)];
        }
        return s;
    }

    // stackalloc inside the loop: every iteration takes 64 more bytes of
    // stack, and none of it is released until the method returns.
    static long StackallocInLoop(long n)
    {
        long s = 0;
        for (long i = 0; i < n; i++)
        {
            Span<long> buf = stackalloc long[8];
            buf[(int)(i & 7)] = i;
            s += buf[(int)(i & 7)];
        }
        return s;
    }

    static void Measure(string name, Func<long, long> f)
    {
        const long n = 50_000_000;
        long sink = 0;
        for (int w = 0; w < 5; w++) sink += f(n);
        int g0 = GC.CollectionCount(0);
        var sw = System.Diagnostics.Stopwatch.StartNew();
        sink += f(n);
        sw.Stop();
        Console.WriteLine($"{name,-10} {sw.Elapsed.TotalMilliseconds * 1e6 / n,6:F2} ns/iter  gen-0 collections: {GC.CollectionCount(0) - g0,4}  ({sink & 1})");
    }

    static void Main(string[] args)
    {
        if (args.Length > 0)
        {
            Console.WriteLine($"stackalloc in a loop, {args[0]} iterations");
            Console.WriteLine(StackallocInLoop(long.Parse(args[0])));
            return;
        }
        Console.WriteLine(System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription);
        Measure("struct", WithStruct);
        Measure("class", WithClass);
        Measure("stackalloc", WithStackalloc);
    }
}
$ dotnet build -c Release && dotnet bin/Release/netcoreapp2.1/structs.dll
.NET Core 4.6.26515.07
struct       0.38 ns/iter  gen-0 collections:    0  (0)
class        2.42 ns/iter  gen-0 collections:  254  (0)
stackalloc   0.21 ns/iter  gen-0 collections:    0  (0)

(The runtime really does describe itself as “.NET Core 4.6.26515.07”: that is the build number of the 2.1 runtime.) The class version made the garbage collector run 254 times in 50 million iterations. The struct version never did. .NET’s JIT does not do the escape analysis HotSpot does, so a class allocated in a loop stays allocated. The programmer has to choose struct.

stackalloc is C#’s way to put a buffer of any size on the stack. Since C# 7.2, released last November, it can be assigned to a Span<T> without an unsafe block, and .NET Core 2.1 is the first runtime with Span<T> built in. It is C’s alloca: the size can be a run-time value, and the memory lasts until the method returns, not until the end of the block. Put it inside a loop and every iteration takes more stack:

$ for n in 1000 100000 1000000 10000000; do dotnet bin/Release/netcoreapp2.1/structs.dll $n 2>&1 | tail -1; done
499500
4999950000
Process is terminating due to StackOverflowException.
Aborted
Process is terminating due to StackOverflowException.
Aborted

A hundred thousand iterations use 6.4 MB of the main thread’s 8 MB stack and survive. A million want 64 MB and kill the process. Go has no equivalent: a size not known at compile time goes on the heap, and a goroutine’s stack holds only what the compiler could measure.

C++ chooses for you, sometimes

In C++ the programmer chooses: a local Point p{...} is on the stack, and new Point{...} is on the heap. Or so the language suggests. Since C++14 the standard has allowed a compiler to remove a new whose result is not needed outside the code it can see, and to merge or omit the matching delete. Three functions that do the same arithmetic:

#include <memory>

struct Point { long x, y; };

// A heap object that never outlives the function.
long viaNew(long i) {
    Point *p = new Point{i, i + 1};
    long s = p->x + p->y;
    delete p;
    return s;
}

// The same, owned by a unique_ptr.
long viaUnique(long i) {
    auto p = std::make_unique<Point>(Point{i, i + 1});
    return p->x + p->y;
}

// On the stack, as C++ would normally write it.
long viaValue(long i) {
    Point p{i, i + 1};
    return p.x + p.y;
}

Which of them call the allocator? The object file’s relocations say:

$ g++ -O2 -std=c++14 -c newpoint.cpp -o np.o && objdump -dr -C np.o | grep -E '^[0-9a-f]+ <|operator (new|delete)'
0000000000000000 <viaNew(long)>:
			a: R_X86_64_PLT32	operator new(unsigned long)-0x4
			25: R_X86_64_PLT32	operator delete(void*, unsigned long)-0x4
0000000000000030 <viaUnique(long)>:
			43: R_X86_64_PLT32	operator new(unsigned long)-0x4
			5a: R_X86_64_PLT32	operator delete(void*, unsigned long)-0x4
0000000000000070 <viaValue(long)>:
$ clang++-6.0 -O2 -std=c++14 -c newpoint.cpp -o np.o && objdump -dr -C np.o | grep -E '^[0-9a-f]+ <|operator (new|delete)'
0000000000000000 <viaNew(long)>:
0000000000000010 <viaUnique(long)>:
0000000000000020 <viaValue(long)>:
$ objdump -d --no-show-raw-insn -C np.o | sed -n '/<viaNew(long)>:/,/^$/p'
0000000000000000 <viaNew(long)>:
   0:	lea    (%rdi,%rdi,1),%rax
   4:	add    $0x1,%rax
   8:	retq
   9:	nopl   0x0(%rax)

gcc 7.3 calls operator new and operator delete in both heap versions, exactly as written. clang 6.0 calls neither: it saw that the object never escapes and removed the allocation, so all three functions compile to the same addition. That is escape analysis, done by an optimiser in a language that never promised it. Which compiler you use decides whether the heap is involved.

Rust makes you say it, and builds it on the stack first

Rust is explicit. Values live on the stack; Box::new(v) puts v on the heap. There is no analysis to read, because there is nothing to decide. But Box::new is an ordinary function that takes its argument by value, and the argument has to exist before the call:

// Box::new takes its argument by value: the 16 MB array is built
// first, and only then moved into the heap allocation.
fn main() {
    let b = Box::new([1u8; 16 << 20]);
    println!("b[12345] = {}, {} bytes on the heap", b[12345], b.len());
}
$ rustc -o boxdbg boxbig.rs && ./boxdbg

thread 'main' has overflowed its stack
fatal runtime error: stack overflow
Aborted
$ rustc -O -o boxrel boxbig.rs && ./boxrel

thread 'main' has overflowed its stack
fatal runtime error: stack overflow
Aborted

The program asks for 16 MB on the heap and dies of a stack overflow, with or without optimisation: Rust 1.26 builds the array in the 8 MB main stack first. Go would have put an array that size on the heap without being asked, as elevenMB showed.

And the languages with no stack objects at all

In CPython every value is a heap object: an integer, a float, a tuple. The interpreter has no escape analysis because it has nothing to put on the stack; its answer to the cost is free lists and a small-object allocator. PyPy, the Python implementation with a JIT, does what HotSpot does: its tracing JIT turns objects that do not escape a loop into plain registers (“virtuals”, in PyPy’s terms). Erlang has no stack-allocated compound terms either. Small integers and atoms are stored directly in a machine word, but tuples, lists and binaries live on the process’s heap, which, as Part 1 showed, is the same block of memory as the process’s stack.

So there are four answers to “who decides where this lives?”:

Who decidesLanguagesWhat it costs you
the programmer, by type or by callC, C++, C#, Rustnothing hidden, everything spelled out; big values can still overflow the stack
the compiler, at build timeGo (and C++ optimisers, unasked)invisible unless you ask with -m; one change can flip it
the JIT, at run timeJava (HotSpot), PyPyinvisible, and can differ between runs
nobody: nearly everything on the heapCPython, Erlangalmost every value costs an allocation; the runtime makes that cheap instead

What this means for Go code

Look before you guess. go build -gcflags=-m prints every decision. -m -m explains each one. go test -bench . -benchmem shows what they cost. Both are cheap enough to run on every change to a hot path.

Return small structs by value. Copying 16 or 32 bytes is cheaper than allocating them. The &T{...} constructor pattern allocates unless it is inlined, and whether it is inlined can change when its body grows.

Let the caller provide the memory. A function that fills a buffer the caller passed in, like io.Reader.Read, lets the caller decide where the buffer lives and reuse it. A function that returns a new buffer forces an allocation on every call.

Know where the walls are. An interface method call, a closure that is stored, a go statement, a variable-length make, anything over 64 KB: each one means the heap. In code that runs a million times a second, each is worth a second look. In code that runs once, none of it matters.

A note on the evidence

What ran. Go 1.10.3 (go1.10.3.linux-amd64.tar.gz, checked against its published SHA-256), released on 5 June 2018, on an Ubuntu 18.04 userland as released: gcc 7.3.0, clang 6.0.0 and OpenJDK 8u162 from its release pocket. Rust 1.26.2 is the release tarball from static.rust-lang.org (checksum verified). .NET Core is the 2.1.300 SDK with runtime 2.1.0, released on 30 May 2018, from Microsoft’s archive, its SHA-512 matching Microsoft’s release metadata. Everything ran in a chroot on a 24-thread x86-64 machine under the host’s Linux kernel, with an 8 MB stack limit (ulimit -s). The sumLoud timing includes a real write system call, and the C# and Rust overflows depend on that 8 MB limit; the allocation counts and the compilers’ decisions depend on neither.

What was measured. Each Go figure is the median of five runs of go test -bench . -benchmem -count 5, all in one sitting with nothing else running. The Java and C# figures are single timed runs of 50 million iterations after a warm-up of 10 (Java) or 5 (C#) runs. They are there to show allocations and collections, which were the same on every run, and the timings only to show their order of magnitude. The C++ result is read from the disassembly, not timed.

What is quoted. The Go compiler source is from the go1.10.3 tag (esc.go, go.go, walk.go). The Go FAQ is quoted from doc/go_faq.html at the same tag. HotSpot’s default is from Oracle’s documentation for Java SE 6u23 and later. The inlining budget of 80 nodes is the constant in inl.go at the tag.

What changed in the writing. The first version of the sumLoud benchmark sent its output to /dev/null opened read-only, so every write failed. It reported 3 allocations per call, two of them error values from the failed writes, which a memory profile showed came from os.(*File).Write and syscall.write. The benchmark above opens /dev/null for writing, and sumLoud allocates once. The first C# version used stackalloc inside the timed loop, which is how the StackOverflowException section came about.

More