← Writing

One Program, Seven Runtimes

30 min readSystemsGORuntimeMemoryGcComparison
Contents

In the last part of this series on Go’s stack and heap, eight versions of one program build the same data: a table of a million entries, a binary tree of two million nodes, and 65 million short-lived nodes that are built and thrown away. In Go 1.16 a goroutine that sleeps for a millisecond at a time wakes up to 18 ms late while that happens; in Java with ZGC, 1.2 ms; in CPython, 0.7 seconds, because Python’s cycle collector stops everything to look at three million objects, 86 times. When the work is done and everything is dropped, Go 1.16 hands back 260 MB within half a minute, and the same program built with Go 1.15 never does as far as top and RSS can tell, although its runtime released the memory just as promptly.

This is the last part of a series on how Go manages the stack and the heap, and it puts Go next to everything the series has compared it with, in one experiment. One workload, written idiomatically in Go, C, C++, Rust, Java, C#, Python and Erlang, run in the same virtual machine on the same kernel, with three questions asked of each: how long the program is made to wait while memory is managed, how deep it can recurse, and how much memory it holds and gives back. The answers line up with what the earlier parts found piece by piece, and they come with the one change in Go 1.16 that belongs in this series: the runtime now releases memory with MADV_DONTNEED again.

This is Part 8 of a series on how Go manages the stack and the heap. Part 1 covered goroutine stacks, Part 4 the collector, Part 5 the memory the runtime hands back, and Part 6 how the runtime stops a goroutine. Everything here ran on Go 1.16, released on 16 February, and Go 1.15.8, with gcc 9.3, Rust 1.50, OpenJDK 11 and 15, .NET 5, CPython 3.9 and Erlang/OTP 23, on Ubuntu 20.04. The note at the end says what was measured and how.

The workload

Eight languages make seven runtimes, because the C and C++ versions share one: glibc’s allocator under code compiled by gcc. Every version does the same five things, in the way that language would normally do them.

  1. Build a table of 1,000,000 entries, each a small node keyed by an integer, and keep it.
  2. Build one tree of depth 20, 2,097,151 nodes, and keep it.
  3. Churn: build 2,000 trees of depth 14, 32,767 nodes each, count each one, and drop it. That is 65,534,000 nodes allocated and abandoned.
  4. Meanwhile, a second thread (a goroutine in Go, a process in Erlang) sleeps for 1 ms at a time and records how late it wakes. That is the program’s own view of every pause: the collector’s, the scheduler’s, the interpreter’s.
  5. Then drop the table and the tree, ask the runtime to collect, and sample the resident set every so often for a minute.

A node is two pointers and a 64-bit integer in every language that has pointers: a struct in Go, C, C++ and Rust (with Box and std::unique_ptr owning the children in the last two), a class in Java and C#, a class with __slots__ in Python, and a three-tuple in Erlang. The table is the language’s usual map: Go’s map, a hand-written open-addressing table in C, std::unordered_map, Rust’s HashMap, Java’s HashMap, C#’s Dictionary, a Python dict and an Erlang map. C, C++ and Rust free memory explicitly and use glibc’s malloc; the others collect. Here is the Go version, which the others follow line for line:

// forest: the Part 8 workload. A table of 1,000,000 entries and one tree of
// depth 20 stay alive; 2,000 trees of depth 14 are built and dropped; a goroutine
// that sleeps for 1 ms at a time records how late it wakes. Then everything is
// dropped, collected, and resident memory watched for a minute.
package main

import (
	"fmt"
	"io/ioutil"
	"runtime"
	"sort"
	"strconv"
	"strings"
	"time"
)

type Node struct {
	left, right *Node
	value       int64
}

func build(d int, v int64) *Node {
	if d == 0 {
		return &Node{value: v}
	}
	return &Node{build(d-1, 2*v), build(d-1, 2*v+1), v}
}

func count(n *Node) int64 {
	if n == nil {
		return 0
	}
	return 1 + count(n.left) + count(n.right)
}

// statusMB reads a field such as VmRSS from /proc/self/status, in MB.
func statusMB(field string) int64 {
	b, _ := ioutil.ReadFile("/proc/self/status")
	for _, l := range strings.Split(string(b), "\n") {
		if strings.HasPrefix(l, field+":") {
			kb, _ := strconv.ParseInt(strings.Fields(l)[1], 10, 64)
			return kb / 1024
		}
	}
	return -1
}

func since(t time.Time) int64 { return time.Since(t).Milliseconds() }

func main() {
	fmt.Println("runtime:", runtime.Version())
	stop := make(chan bool)
	late := make(chan []float64)
	go func() {
		var l []float64
		for {
			select {
			case <-stop:
				late <- l
				return
			default:
			}
			t := time.Now()
			time.Sleep(time.Millisecond)
			l = append(l, float64(time.Since(t)-time.Millisecond)/1e6)
		}
	}()

	t := time.Now()
	table := make(map[int64]*Node)
	for i := int64(0); i < 1000000; i++ {
		table[i] = &Node{value: i}
	}
	fmt.Printf("table:   %d ms\n", since(t))
	t = time.Now()
	tree := build(20, 1)
	fmt.Printf("tree:    %d ms\n", since(t))
	t = time.Now()
	var nodes int64
	for i := 0; i < 2000; i++ {
		nodes += count(build(14, int64(i)))
	}
	fmt.Printf("churn:   %d ms  (%d nodes)\n", since(t), nodes)

	stop <- true
	l := <-late
	sort.Float64s(l)
	fmt.Printf("hiccups: max %.1f ms, p99 %.1f ms, %d samples\n", l[len(l)-1], l[len(l)*99/100], len(l))
	fmt.Printf("peak:    %d MB\n", statusMB("VmHWM"))
	fmt.Printf("live:    %d MB  (%d entries, %d nodes)\n", statusMB("VmRSS"), len(table), count(tree))

	table, tree = nil, nil
	runtime.GC()
	fmt.Printf("after collection:  %d MB\n", statusMB("VmRSS"))
	start := time.Now()
	for _, s := range []int{10, 30, 60} {
		time.Sleep(time.Until(start.Add(time.Duration(s) * time.Second)))
		fmt.Printf("after %d s idle:   %d MB\n", s, statusMB("VmRSS"))
	}
}

The test bed is Ubuntu 20.04 as it was released, in a QEMU virtual machine booted on the release’s own kernel, 5.4.0-26, with four processors and 6 GB of memory: small enough that the runtimes have to share, big enough that none of them runs out. Each runtime’s newest release before this post: Go 1.16 and 1.15.8; gcc and g++ 9.3 with glibc 2.31; Rust 1.50.0; OpenJDK 11.0.10 and 15.0.2; .NET 5.0.3; CPython 3.9.1; and Erlang/OTP 23.2.7. Every version ran three times, in three separate boots, with nothing else on the machine. A run of the Go version:

$ bin/forest-go1.16
runtime: go1.16
table:   162 ms
tree:    39 ms
churn:   1181 ms  (65534000 nodes)
hiccups: max 18.3 ms, p99 11.9 ms, 975 samples
peak:    289 MB
live:    289 MB  (1000000 entries, 2097151 nodes)
after collection:  289 MB
after 10 s idle:   289 MB
after 30 s idle:   28 MB
after 60 s idle:   28 MB

Speed is not the point here, but it frames the rest. The median churn took 1.2 s in Go 1.16, 1.3 s in C and Rust, 1.4 s in C++, 0.44 to 0.84 s in Java depending on the collector, 0.69 s in .NET, 1.6 s in Erlang and 59 s in CPython. The JVM and .NET, with moving, generational collectors, are the fastest at making garbage, which is what Part 4 would predict: allocation is a pointer bump, and a dead young object costs nothing to collect. C, C++ and Rust pay malloc and free for each of 65 million nodes. Go, which neither moves objects nor separates generations, lands next to C.

Eight ways to write one tree

The programs are the same shape, but what the language does with a node is not, and the difference shows before anything is measured.

In C, every node is a malloc and, eventually, a free, and the program says when:

static Node *build(int d, int64_t v) {
    if (d == 0) return node(NULL, NULL, v);
    Node *l = build(d - 1, 2 * v);
    return node(l, build(d - 1, 2 * v + 1), v);
}
static int64_t count(Node *n) { return n ? 1 + count(n->left) + count(n->right) : 0; }
static void drop(Node *n) { if (n) { drop(n->left); drop(n->right); free(n); } }

Freeing a tree is a walk over it, recursive like the building, one free per node. Rust writes the same tree with the ownership in the types, and the walk disappears from the source:

struct Node {
    left: Option<Box<Node>>,
    right: Option<Box<Node>>,
    value: i64,
}

and in the churn loop

        nodes += count(&Some(build(14, i)));

the tree is a temporary, so it is dropped at the end of the statement: the compiler generates the same recursive walk and the same free per node that drop does in C. C++ with std::unique_ptr does exactly the same, through destructors. All three free a tree the moment it is no longer wanted, and all three free it by recursion, on the thread’s fixed stack. For a tree of depth 14 or 20 that is no problem; a linked list of a million nodes, freed the same way, would recurse a million deep, and a later section shows what a million-deep recursion does to these stacks.

Go, Java and C# write the node as a struct or class with two references, allocate with &Node{...} or new, and never free anything. The garbage is found later, by the collector, and the cost of a dead node depends on the collector: nothing at all in a moving generational collector that never touches it, a sweep of its span in Go’s.

Python writes a class, and the __slots__ line is there to make the comparison fair:

class Node:
    __slots__ = ("left", "right", "value")

Without it every node would carry its own attribute dictionary. With it a node is 56 bytes, all of them in CPython’s small-object allocator, each with a reference count and the two links the cycle collector uses to track it. Reference counting frees a node the moment the last reference goes, so in CPython, as in C, a dropped tree is freed at once, by a recursive walk, here inside the interpreter. The cycle collector exists only for what reference counting cannot free, and this program never makes a cycle. That is worth remembering when it comes to the pauses.

Erlang has no mutable memory at all. A node is a tuple, and building a tree is building tuples:

build(0, V) -> {nil, nil, V};
build(D, V) -> {build(D - 1, 2 * V), build(D - 1, 2 * V + 1), V}.

The table is a map, and an Erlang map cannot be changed, only replaced by a new one with one more key:

table(Map, 1000000) -> Map;
table(Map, I) -> table(Map#{I => {nil, nil, I}}, I + 1).

A map that large is a hash array mapped trie, so each insertion copies the path from the root to the new key and leaves the old path as garbage. That is probably most of why building the table took Erlang about 626 ms, four times as long as Go and ten times as long as C++; I did not measure the garbage it made. The trees cost nothing of the kind, because a tuple is built once and never updated. And every one of these terms lives in the heap of the one process that built them, which no other process can see; that is what lets each Erlang process collect on its own.

Pauses as the program sees them

How late a thread that sleeps for 1 ms woke up

While the work ran. Milliseconds, log scale; median of three runs.

99th percentileworsta diagnostic run, not the workload as written
Go 1.16
10.8 / 18.3
Go 1.16, madvdontneed=0
10.9 / 16.0
Go 1.15.8
11.8 / 18.8
C
0.2 / 0.4
C++
0.2 / 0.3
Rust 1.50
0.2 / 0.5
Java 11, G1
4.5 / 8.0
Java 15, G1
5.4 / 8.7
Java 15, ZGC
0.4 / 1.2
.NET 5
7.6 / 9.3
CPython 3.9
592.1 / 692.4
Erlang/OTP 23
2.8 / 4.0
Go 1.16, GOGC=off
0.3 / 0.4
CPython, cycle collector off
5.8 / 19.7
0.11101001000

Hover or focus a row for all three runs.

The figure is the 99th percentile and the worst of how late the sleeper woke, during the work, median of three runs. Three groups stand out.

No collector, no pauses. In C, C++ and Rust the median worst wait was half a millisecond or less, and the worst of all nine runs 1.5 ms; the 0.2 ms at the 99th percentile is the kernel’s timer slack and the cost of waking a thread. Freeing 65 million nodes one by one costs time, but it is spent on the thread doing the work, not taken from the others.

Collectors with pauses of a few milliseconds. Erlang’s sleeper waited 2.8 ms at the 99th percentile, Java with G1 4.5 to 5.4 ms, and .NET’s workstation collector 7.6 ms. Erlang’s number is the one the earlier parts predict: each Erlang process has its own heap and its own collector, so the tree-building process collecting its own heap does not stop the sleeper, which only waits for a scheduler. G1 and .NET stop every thread for their young collections, and these are the stops. And Java 15’s ZGC, which does nearly all its work concurrently, kept the 99th percentile at 0.4 ms and the worst at 1.2 ms.

Go, 11 ms at the 99th percentile. That is not what Part 4 measured. There, Go’s stops of the world took under 0.6 ms, and the collector traced here is the same one. A trace shows what happens:

$ GODEBUG=gctrace=1 bin/forest-go1.16 2>&1 | grep -E '^gc (9|10|11) |churn|hiccups'
gc 9 @0.405s 10%: 0.011+30+0.021 ms clock, 0.045+8.9/30/53+0.087 ms cpu, 233->248->124 MB, 247 MB goal, 4 P
gc 10 @0.500s 9%: 0.010+28+0.021 ms clock, 0.041+8.9/27/52+0.087 ms cpu, 234->251->126 MB, 249 MB goal, 4 P
gc 11 @0.593s 9%: 0.012+27+0.023 ms clock, 0.050+6.6/27/54+0.093 ms cpu, 235->254->128 MB, 252 MB goal, 4 P
churn:   1118 ms  (65534000 nodes)
hiccups: max 16.9 ms, p99 10.4 ms, 899 samples

The two stops of each cycle, the first and last numbers of the clock column, took 10 to 23 microseconds. What lasts is the concurrent mark between them: 27 to 30 ms of the 93 ms or so between cycles, so the collector is marking about a third of the time. And with the collector turned off, the lateness disappears:

$ GOGC=off bin/forest-go1.16 | head -6
runtime: go1.16
table:   153 ms
tree:    40 ms
churn:   1446 ms  (65534000 nodes)
hiccups: max 0.4 ms, p99 0.2 ms, 1466 samples
peak:    1741 MB

In three runs with GOGC=off the worst wake-up was 0.4 to 0.5 ms. So the delays come from concurrent marking, not from the stops. The cpu column of the trace says where the marking runs: the third figure of the middle group, 52 to 54 ms of CPU per cycle, is idle marking. When a processor has nothing to run during a cycle, the runtime gives it an idle mark worker, which keeps marking until there is something better to do. In Go 1.16 an idle worker checks for that with pollWork in proc.go:

func pollWork() bool {
	if sched.runqsize != 0 {
		return true
	}
	p := getg().m.p.ptr()
	if !runqempty(p) {
		return true
	}
	if netpollinited() && atomic.Load(&netpollWaiters) > 0 && sched.lastpoll != 0 {
		if list := netpoll(0); !list.empty() {
			injectglist(&list)
			return true
		}
	}
	return false
}

Runnable goroutines and network events count; a timer that has come due does not. Since Go 1.14 each processor keeps its own timers, as Part 6 described, so my reading is this: the sleeper’s timer sits on a processor that an idle worker has taken, and fires when that worker next lets go, up to the 10 ms scheduling quantum later. Idle workers once always ran for the whole quantum; issue #16528 made them yield to runnable goroutines and network packets, in a fix of November 2016. The figure’s 11 ms and the quantum’s 10 ms fit; I have not traced it inside the runtime. Raising GOMAXPROCS to 8 on the same four processors did not help (6.8 ms at the 99th percentile, 18.3 ms worst, one run). On the 24-thread host itself, in an earlier and shorter version of the workload, the sleeper was late by about a millisecond; that fits a free processor being nearer, but that run differed in more than one way.

What the sleeper measures is narrow on purpose. It is one thread that does no work, so it sees the program’s stops and the scheduler’s delays and nothing of the time the work itself lost to the collector; that is in the churn times. It also asks to wake at one particular moment, which is exactly the case where a stalled timer shows, and a thread blocked on a channel or a socket might not see the same delay at all.

None of Go’s delay is a pause in the sense the release notes mean: the program never stops. A request served by a goroutine already running is not affected. A goroutine waiting on a timer, a time.Sleep, a time.After or a ticker, can be.

CPython, 0.6 seconds at the 99th percentile. The interpreter makes a thread holding the global interpreter lock hand it over every 5 ms (sys.getswitchinterval()), so a sleeping thread should be about that late, and it was late by more than a hundred times that. Timing every run of the cycle collector shows why:

$ python3 -u pydiag.py | tail -3
generation 0: 88310 collections, longest 0.7 ms, total 1271 ms
generation 1: 8028 collections, longest 0.9 ms, total 1618 ms
generation 2: 86 collections, longest 640.2 ms, total 42128 ms

Eighty-six full collections, each walking every container object in the process, three million and more, in C, without letting go of the interpreter lock. The longest took 640 ms, the same as the sleeper’s worst wait, and together they took 42 of the churn’s 57 seconds. CPython runs a full collection when the objects promoted since the last one reach a quarter of all the long-lived ones, a rule in gcmodule.c that dates from 2008 and exists to stop a program that builds a big structure from paying a full collection every few thousand allocations. Here it does not help, because every churn tree is built recursively and most of its 32,767 nodes survive the two young generations before the tree is dropped. About twenty-four trees later a quarter of the long-lived total has been counted as promoted, and the next full collection walks three million live nodes and frees nothing, because reference counting freed each of those trees the moment it was dropped. The same program with the cycle collector disabled:

$ python3 -u pydiag.py off | sed -n 4,5p
churn:   13583 ms  (65534000 nodes)
hiccups: max 19.7 ms, p99 5.8 ms, 2224 samples

The churn took 13.6 s instead of 57, and the sleeper’s 99th percentile came down to the 5 ms of the interpreter lock. The cycle collector was looking for cycles that the program never made. gc.freeze(), added in 3.7, moves everything alive at one moment out of the collector’s sight, and is meant for a program that builds its long-lived data first.

A million calls deep

A separate program in each language recursed a million calls deep, on the main thread, with nothing else: depth(n) = depth(n-1) + 1. The C and Rust versions read a volatile copy of the argument after the call so the compiler cannot turn the recursion into a loop.

$ bin/depth-go
go1.16: depth 1000000 reached in 32 ms, stack in use 32 MB
$ erl -noshell -s depth main
Erlang: depth 1000000 reached in 28 ms, process heap now 9 MB
$ java Depth
Java: StackOverflowError after 20361 calls
$ python3 depth.py
Python: RecursionError after 999 calls: maximum recursion depth exceeded in comparison
$ bin/depth-c
Segmentation fault
$ bin/depth-rust

thread 'main' has overflowed its stack
fatal runtime error: stack overflow
Aborted
$ dotnet Depth.dll
Stack overflow.
Repeat 261817 times:
--------------------------------
   at Depth.D(Int32)

Two of seven get there, and they are the two whose stacks are not fixed. Go grew the goroutine’s stack by copying it, as Part 1 showed, to 32 MB, in 32 ms. Erlang’s stack lives inside the process’s heap and grows with it. Every other runtime runs on the thread’s stack, 8 MB for this main thread (ulimit -s), and stops where it ends. They differ only in how they stop. C dies of SIGSEGV on the guard page. Rust puts a guard page under every thread and a handler for it that says what happened before aborting. .NET 5 prints the frames, compressed: 261,817 of them, which comes to about 32 bytes each in 8 MB. Java’s main thread is a thread of its own, 1 MB by default, and in this one run the 20,361 calls ended in an exception the program catches; HotSpot’s depth varies with what the JIT has compiled. And CPython stops at its own recursion limit of 1,000 frames, long before the C stack under the interpreter would run out.

How much memory

Resident memory: at the peak, after collecting, after a minute idle

MB, log scale; median of three runs. The live data is the same in every runtime.

peakright after collectionafter 60 s idle
Go 1.16
289 / 289 / 27
Go 1.16, madvdontneed=0
294 / 294 / 294
Go 1.15.8
353 / 353 / 353
C
128 / 95 / 95
C++
139 / 128 / 128
Rust 1.50
130 / 96 / 96
Java 11, G1
835 / 51 / 51
Java 15, G1
581 / 54 / 54
Java 15, ZGC
2,141 / 2,147 / 2,147
.NET 5
208 / 140 / 141
CPython 3.9
338 / 35 / 35
Erlang/OTP 23
641 / 359 / 20
101001,0003,000

Values are peak / after collection / after 60 s idle. Java 15 with ZGC maps its heap more than once, and RSS counts it each time: its proportional set size, read as the work finished in a separate run, was 1.2 GB, not 2.1.

The live data is the same everywhere: three million nodes and a table. At the peak, C, C++ and Rust held 128 to 139 MB, close to the data itself, three million 24-byte nodes in 32-byte malloc chunks plus the table. Everything else held more, and how much more is a policy each runtime chose.

Go held 289 MB with 1.16 and 353 MB with 1.15.8, a little over twice the live data, because the collector lets the heap grow to twice what survived the last cycle before it starts the next (GOGC=100, Part 4). The trace above shows it: 124 to 133 MB live after each cycle, a 247 to 266 MB goal. Why 1.15.8 peaks 60 MB higher I did not trace; it is not the madvise setting, since 1.16 with madvdontneed=0 peaked at 294 MB.

Java held 581 to 835 MB with G1. HotSpot sizes the heap from the machine, up to a quarter of its memory here, and G1 grows it to keep collection time down. More room means fewer collections; the JVM used it.

ZGC’s resident set read 2.1 GB, about twice what it really held. ZGC maps the same physical heap at several addresses, one view for each colour a pointer can carry, and a page touched through two views is counted twice in the resident set. The breakdown, from a separate run, read as the work finished:

$ grep -E '^(VmRSS|RssShmem)' /proc/$pid/status; grep -E '^(Pss|Pss_Shmem):' /proc/$pid/smaps_rollup
VmRSS:	 2181988 kB
RssShmem:	 2108976 kB
Pss:             1184589 kB
Pss_Shmem:       1111371 kB

The proportional set size, which divides a shared page among its mappings, is 1.2 GB, which matches the 1,122 MB of heap capacity jcmd reported. That is still the most of any runtime here, by a lot: ZGC trades memory for its millisecond.

.NET held 208 MB, CPython 338 MB, Erlang 641 MB. CPython’s nodes are objects of 56 bytes, with reference counts and the cycle collector’s links, and the table’s keys are integer objects of their own. Erlang’s peak is probably a copy: a process’s collector copies its live data to a new, bigger heap, so for a moment old and new heaps exist together. By the end of the work it was resident at 441 MB.

Giving it back

The more interesting numbers are what each runtime held after everything was dropped and collected, and a minute later.

C, C++ and Rust kept 95 to 128 MB of the 128 to 139. Every node was freed. But glibc returns memory on its own only from the top of its heap, when a free leaves enough room there, and small freed chunks wait in bins that are not merged with their neighbours when they are freed. A C-only version of the same allocations, trim.c, with an array where forest.c has its hash table, shows what is left; its output is in console order:

$ bin/trim
live:              103 MB
after free:        96 MB
Arena 0:
system bytes     =  100159488
in use bytes     =       6512
Total (incl. mmap):
system bytes     =  100159488
in use bytes     =       6512
max mmap regions =          1
max mmap bytes   =    8003584
after malloc_trim: 0 MB

A hundred megabytes held for 6.5 kilobytes in use, all of it returned by one call to malloc_trim(0), which walks the whole heap rather than only its top. A C program does not leak here; its allocator is keeping memory for the next malloc, as the Go runtime does, but with no scavenger to hand it back. I checked this only for C; C++ kept more, 128 MB, and I did not break that down.

Java with G1 dropped to about 52 MB at once. System.gc() makes G1 run a full collection, and after one it shrinks the heap to what its free-ratio settings allow, returning the rest. ZGC’s resident set stayed at 2.1 GB, about 1.1 GB of it real, for the whole minute. Its ZUncommitDelay flag is 300 seconds by default, and by its documentation ZGC uncommits memory only after that long unused; I did not wait to see it. .NET kept 140 MB, the same after a minute. CPython dropped to 35 MB: its object allocator frees a 256 KB arena as soon as the last object in it dies. Erlang dropped to 359 MB after the collection and to 20 MB by the first idle sample, ten seconds later, the smallest of all; I did not trace whether the main process’s next collection or the allocator returning its carriers made the difference.

And Go: 1.16 held 289 MB after the collection, and 27 MB half a minute later. 1.15.8 held 353 MB for the whole minute. The same source, built with two releases twelve days apart.

What Go 1.16 changed

Part 5 described what happened in Go 1.12: on Linux the runtime started returning free pages with madvise(MADV_FREE) rather than MADV_DONTNEED. Both tell the kernel the pages are not needed. With MADV_DONTNEED the kernel takes them away at once and the resident set falls. With MADV_FREE it takes them only when it needs memory, and until then they still count as resident. Part 5 measured the result on Go 1.13: RSS that did not fall until something else on the machine wanted the memory. GODEBUG=madvdontneed=1 switched back.

Go 1.16 makes that the default. The release notes:

On Linux, the runtime now defaults to releasing memory to the operating system promptly (using MADV_DONTNEED), rather than lazily when the operating system is under memory pressure (using MADV_FREE). This means process-level memory statistics like RSS will more accurately reflect the amount of physical memory being used by Go processes.

and the reasoning, in runtime1.go:

	if GOOS == "linux" {
		// On Linux, MADV_FREE is faster than MADV_DONTNEED,
		// but doesn't affect many of the statistics that
		// MADV_DONTNEED does until the memory is actually
		// reclaimed. This generally leads to poor user
		// experience, like confusing stats in top and other
		// monitoring tools; and bad integration with
		// management systems that respond to memory usage.
		// Hence, default to MADV_DONTNEED.
		debug.madvdontneed = 1
	}

The scavenger is not what differs: both releases return the memory as quickly. A smaller program keeps the same data alive through the churn, drops it, collects, and then reads HeapReleased every second next to the resident set:

$ bin/release-go1.16 | sed -n 3,6p
 0 s  RSS  305 MB  HeapIdle  319 MB  HeapReleased   38 MB  GCs 19
 1 s  RSS  305 MB  HeapIdle  319 MB  HeapReleased   38 MB  GCs 19
 2 s  RSS  132 MB  HeapIdle  319 MB  HeapReleased  209 MB  GCs 19
 3 s  RSS   28 MB  HeapIdle  319 MB  HeapReleased  317 MB  GCs 19
$ bin/release-go1.15.8 | sed -n 3,6p
 0 s  RSS  365 MB  HeapIdle  383 MB  HeapReleased   45 MB  GCs 20
 1 s  RSS  365 MB  HeapIdle  383 MB  HeapReleased   44 MB  GCs 20
 2 s  RSS  365 MB  HeapIdle  383 MB  HeapReleased  333 MB  GCs 20
 3 s  RSS  365 MB  HeapIdle  383 MB  HeapReleased  381 MB  GCs 20

Both runtimes returned everything idle within three seconds: HeapReleased climbs to HeapIdle in both. In 1.16 the resident set follows it down. In 1.15.8 the pages were given back with MADV_FREE, and the kernel, with plenty of memory to spare, left them where they were, counted as resident, for the rest of the minute. 1.16 with GODEBUG=madvdontneed=0 behaves exactly as 1.15.8 does, 305 MB to the end. The memory was free in all three; only one of them shows it.

The switch has a cost, and Part 5 measured it. A page returned with MADV_FREE and then written again comes back without the kernel doing anything, because the write simply cancels the advice; a page returned with MADV_DONTNEED has to be faulted in and zero-filled. Refilling a returned gigabyte took 262,156 page faults with MADV_DONTNEED, on Go 1.11, against a dozen with MADV_FREE on Go 1.13, and the refill with MADV_FREE was about a quarter faster. Go 1.16 pays that again for a program whose heap swings up and down, in exchange for a resident set that means what monitoring tools think it means. GODEBUG=madvdontneed=0 puts the old behaviour back for a program that would rather have the faults saved.

When the release happens varies. In the runs that sampled every second, it came within three seconds. In the workload, which slept ten seconds at a time, all three runs still showed about 290 MB at ten seconds and had released by thirty; the smaller program, made to sleep the same way, had released by ten seconds in one run and only by thirty in the other. Some idle Go programs give memory back in seconds and some in half a minute; all of them did within thirty seconds here.

Seven runtimes, one series

Seven parts took Go’s stack and heap apart one piece at a time, on the releases that changed them: the stack that starts at two kilobytes and moves when it grows (Part 1), the compiler’s decision about what lives on it (Part 2), the allocator under every new and the arenas it maps (Part 3), the collector that never moves anything (Part 4), the memory the runtime keeps and when it hands it back (Part 5), the signal that lets it stop a goroutine anywhere (Part 6), and the same runtime on an operating system that hands out memory in two steps (Part 7). Set against each other here, the results say what those parts said one at a time.

  • Stacks. Only Go and Erlang recurse far past a thread’s 8 MB, Go to its 1 GB limit and Erlang to the limit of memory, and both pay for it in a small way on every call: Go’s stack check (Part 1), Erlang’s heap check. Everyone else trusts a fixed stack and a guard page, and the difference between them is only how they die.
  • Allocation. The moving, generational collectors make garbage the cheapest (Java, .NET). Go, which has neither, allocates at about C’s speed; not moving objects is what lets it hand out interior pointers and pass memory to C without pinning (Part 4).
  • Pauses. Every collector stops the program somehow. Go’s stops take tens of microseconds; its concurrent marking is long, and on a small machine it delays timers. CPython’s cycle collector is the one to watch, because it stops everything, in proportion to everything that is alive.
  • Memory. A collector holds more than the live data, by a factor it chooses: two for Go, more for Java, much more for ZGC. And no runtime gives memory back without a policy for it: glibc only from the top, .NET and ZGC on their own schedules, Go with a scavenger that since 1.13 runs in the background (Part 5) and since 1.16 does so visibly.

What is coming

The change in front of the Go runtime now is to its calling convention. Since its first release Go has passed arguments and results on the stack, a convention whose simplicity runs through everything this series has looked at: no register holds a live value across a call, so the collector and the stack copier only ever need to look at stack memory. Proposal #40724, opened last August, moves Go to passing them in registers, and estimates “at least a 5–10% throughput improvement” from the preliminary experiments. What it asks of the stack is spelled out in its design document:

With register-based arguments, morestack will also have to save all argument registers. We propose that it simply spill all possible argument registers rather than trying to be specific to the function; morestack is relatively rare, so the cost is this is unlikely to be noticeable.

The stack check from Part 1 stays, and the moment the stack must grow, the argument registers have to be put somewhere the stack copier can see them. The design document suggests the guard space every stack already keeps below its frame. Whether that works out as planned is a question for a release that has not shipped.

A note on the evidence

What ran. Go 1.16 (16 February 2021) and Go 1.15.8 (4 February), the official linux-amd64 archives checked against their published SHA-256; gcc and g++ 9.3.0 and glibc 2.31 as released in Ubuntu 20.04; Rust 1.50.0 (11 February); AdoptOpenJDK 11.0.10+9 and 15.0.2+7 (January 2021); .NET SDK 5.0.200 with runtime 5.0.3 (2 March; SHA-512 matched Microsoft’s release metadata); CPython 3.9.1 (December 2020), built from source; Erlang/OTP 23.2.7 (3 March), built from the released source tarball, whose SHA-256 matched the release’s checksum file. All of it in an Ubuntu 20.04 userland as released, in a QEMU virtual machine booted on Ubuntu 20.04’s release kernel, 5.4.0-26, with four virtual processors and 6 GB of memory and no swap, on a 24-thread x86-64 host with nothing else running. The main thread’s stack limit was 8 MB.

What was measured. Every workload ran three times, each time in a fresh boot of the VM, and the figures show medians with all three runs in the hover text. The diagnostic runs are fewer, and said so: GOGC=off three times; the GC trace once; the CPython collector timed once and disabled once; the release program twice each on 1.16, 1.16 with madvdontneed=0 and 1.15.8, and twice more on 1.16 in each sampling pattern after release.go gained its ten-second option (the 1.16 output shown is one of those, release-short); trim once; the ZGC breakdown once; each recursion program once. The “more processors” sleeper figure for Go, about a millisecond, is from a shorter version of the workload run directly on the 24-thread host under its own kernel, before the churn was raised to 2,000 trees; GOMAXPROCS=8 in the VM is one run. The ZGC breakdown is from a separate run, and jcmd read the heap after the program had dropped its data. Resident memory is VmRSS and VmHWM from /proc/self/status, read by each program itself.

What changed in the writing. The first version of release.go never used the table or the tree after building them; the compiler saw them as dead, the collector freed them during the churn, and the program ran 401 collections against the workload’s 19. It was changed to use both after the churn, as the workload does, and rerun. The run that timed CPython’s collections kept 302 MB after collecting, not 35 MB: its timing records, small objects allocated all through the run, kept pymalloc arenas alive. Its memory figures are not used.

What is not explained. The idle-worker reading of Go’s late timers is mine, from the source and the two experiments above, not observed inside the runtime. Why the same Go 1.16 binary returns memory after two seconds in one run and between ten and thirty in another, what dropped Erlang’s resident set between the collection and the first idle sample, why Go 1.15.8 peaked 60 MB above 1.16, and how C++’s 128 MB divides between glibc and libstdc++, were not traced. Erlang’s slow table and its peak are explained from how its maps and its collector work, not measured.

What is quoted. Go source from the go1.16 tag (proc.go, runtime1.go); doc/go1.16.html. CPython 3.9.1’s Modules/gcmodule.c and Python/ceval_gil.h. Go issues #16528 (2016) and #40724, and the design document “Proposal: Register-based Go calling convention”, Austin Clements, last updated 10 August 2020.

More