← Writing

A Collector That Never Moves a Thing

Contents

Make 3.2 gigabytes of short-lived garbage in a Go program, and its garbage collector spends 52 milliseconds of CPU cleaning up after it. Or 3,054 milliseconds. The garbage is identical in both runs. The difference is what else the program is holding: half a gigabyte of plain numbers costs the collector almost nothing, and half a gigabyte of objects that hold pointers costs it sixty times as much. Java’s collectors spend a few milliseconds on the same garbage, whichever it is, and .NET gets through all of it in a quarter of a second. Go’s collector does not mind how much garbage there is. It minds what is still alive, and it looks at all of it, every cycle.

This post is about that collector. Go’s runtime describes it in one sentence: it is “a concurrent mark and sweep that uses a write barrier. It is non-generational and non-compacting.” The post takes the sentence apart: how marking can run while the program changes the very pointers being followed, what the write barrier costs in the machine code, how the collector decides when to run, and how to read the one line it prints about every cycle. Then it measures what the collector’s work follows, and sets Go’s choices beside the generational, moving collectors of Java and .NET, with the reasons the Go team gave last summer for not building one.

This is Part 4 of a series on how Go manages the stack and the heap. Part 1 covered goroutine stacks, Part 2 escape analysis, and Part 3 the allocator. It is written for Go programmers who have written a little C. Everything here ran on Go 1.11.4, released on 14 December, on an Ubuntu 18.04 userland, with OpenJDK 11.0.1 and .NET Core 2.1 for the comparisons. The note at the end says what was measured and how.

How a tracing collector works

This section is the theory. If you know mark-sweep, copying and generational collection, skip to the next one.

A tracing garbage collector finds garbage by finding everything that is not garbage. It starts from the roots, the places a program can reach memory from directly: global variables, every goroutine’s stack, registers. It follows every pointer from the roots, and every pointer from what those point to, until it has visited every object the program could still reach. Anything it did not visit is garbage, because no sequence of pointer loads can ever get to it again.

What it does with the garbage divides collectors into two families:

  • Mark-sweep marks every reachable object, then sweeps: goes through the heap and makes every unmarked block available for reuse. Nothing moves. The cost of the mark phase is proportional to the live objects and the pointers in them; the cost of the sweep to the size of the heap.
  • Copying (and its cousin, mark-compact) moves every reachable object to a fresh, contiguous area as it finds it, and then treats everything left behind as free in one go. The cost is proportional to the live objects only: garbage is never even looked at. And because the survivors end up packed together, allocation afterwards is just bumping a pointer through the empty space. The price is moving objects, which means updating every pointer to them.

Most objects die young. This observation, the generational hypothesis, made generational collectors the standard design for managed runtimes. New objects go into a small young generation, which is collected often, by copying. Since most of it is dead by then, a young collection copies very little and finishes quickly, however much garbage was made. Objects that survive a few young collections are promoted to an old generation, which is collected rarely. The catch is that an old object may point to a young one, and a young collection, which does not trace the old generation, has to know about such pointers. So every pointer store into an old object has to be recorded by a few instructions called a write barrier, which slows the program down a little all the time.

The last ingredient is concurrency. A collector that stops the program while it marks (“stop the world”) makes the program pause for as long as marking takes. A concurrent collector marks while the program runs. Then the program can change pointers behind the collector’s back, and the collector needs a write barrier for a different reason: to hear about those changes, so that nothing reachable is missed.

Go’s collector in one paragraph

The comment at the top of src/runtime/mgc.go in Go 1.11.4:

// Garbage collector (GC).
//
// The GC runs concurrently with mutator threads, is type accurate (aka precise), allows multiple
// GC thread to run in parallel. It is a concurrent mark and sweep that uses a write barrier. It is
// non-generational and non-compacting. Allocation is done using size segregated per P allocation
// areas to minimize fragmentation while eliminating locks in the common case.

Every word of it has appeared in this series. Type accurate, or precise: the collector knows which words are pointers, from the type of each heap object and from the stack maps of Part 1, so an integer that looks like an address never keeps anything alive. Mark and sweep: nothing moves, and Part 3’s sweeping turns the mark bits into the next allocation bitmap. Size segregated per P allocation areas: Part 3’s mcaches and size classes, which are how a non-moving collector avoids drowning in fragmentation. What is left is the concurrency and the write barrier, and the two things it does not do: generations and compaction.

Marking while the program runs

Go’s marking uses the classic tri-colour abstraction, which comes from Dijkstra’s 1978 paper on on-the-fly collection, cited by name in mgc.go. Every object is in one of three sets:

  • white: not reached yet. At the end of marking, white means garbage.
  • grey: reached, but its own pointers have not been followed yet. The grey objects are the collector’s to-do list.
  • black: reached, and all its pointers followed.

Marking starts by shading the roots’ targets grey, then repeatedly takes a grey object, shades everything it points to grey, and turns it black. When no grey object is left, marking is done. In the classic algorithm the invariant that makes this correct is that a black object never points to a white one: everything a black object points to has already been shaded. (Go’s barrier keeps a slightly weaker form of it, which is enough: a white object a black one points to is always still reachable through some grey object, so it will be found.)

Marking while the program runs (illustration)

Eight heap objects, two roots, and one pointer the program moves halfway through.

W white: not reached yetG grey: reached, not scannedB black: scanned

The program can break that invariant. Suppose it copies a pointer to a white object into a black object (which the collector will not scan again), and then removes the only other pointer to it, from an object that has not been scanned yet. The white object is still reachable, through the black one, but the collector will never see a pointer to it, and it will be freed while in use.

Go’s write barrier prevents that. Since Go 1.8 it is a hybrid of two classic barriers, described in src/runtime/mbarrier.go:

// Go uses a hybrid barrier that combines a Yuasa-style deletion
// barrier—which shades the object whose reference is being
// overwritten—with Dijkstra insertion barrier—which shades the object
// whose reference is being written. The insertion part of the barrier
// is necessary while the calling goroutine's stack is grey. In
// pseudocode, the barrier is:
//
//     writePointer(slot, ptr):
//         shade(*slot)
//         if current stack is grey:
//             shade(ptr)
//         *slot = ptr

Shading the overwritten pointer means a pointer can never be removed from the heap without its target being shaded. Shading the new pointer covers the case where the only pointer to an object is on a stack that has not been scanned yet. Together they are what let Go 1.8 stop re-scanning stacks with the world stopped at the end of every cycle, which its release notes summed up as “reduces GC pauses by eliminating stop-the-world stack rescanning.”

The barrier is not free, and it is not always on. It is compiled into every store of a pointer into the heap, but it only does anything while marking is running. This program has one function that stores a pointer and one that stores an integer:

package main

type node struct {
	next *node
	v    int
}

// link stores a pointer into a heap object: the compiler guards the
// store with a check of the write-barrier flag.
//go:noinline
func link(a, b *node) { a.next = b }

// count stores an integer: no barrier.
//go:noinline
func count(a *node, v int) { a.v = v }

func main() {
	a, b := new(node), new(node)
	link(a, b)
	count(a, 1)
	println(a.next == b, a.v)
}
$ go build -o wb wb.go && go tool objdump -s 'main\.(link|count)$' wb
TEXT main.link(SB) /work/go-p4/wb.go
  wb.go:11		0x44ebb0		64488b0c25f8ffffff	MOVQ FS:0xfffffff8, CX
  wb.go:11		0x44ebb9		483b6110		CMPQ 0x10(CX), SP
  wb.go:11		0x44ebbd		7639			JBE 0x44ebf8
  wb.go:11		0x44ebbf		4883ec08		SUBQ $0x8, SP
  wb.go:11		0x44ebc3		48892c24		MOVQ BP, 0(SP)
  wb.go:11		0x44ebc7		488d2c24		LEAQ 0(SP), BP
  wb.go:11		0x44ebcb		488b7c2410		MOVQ 0x10(SP), DI
  wb.go:11		0x44ebd0		8407			TESTB AL, 0(DI)
  wb.go:11		0x44ebd2		833d1772080000		CMPL $0x0, runtime.writeBarrier(SB)
  wb.go:11		0x44ebd9		7511			JNE 0x44ebec
  wb.go:11		0x44ebdb		488b442418		MOVQ 0x18(SP), AX
  wb.go:11		0x44ebe0		488907			MOVQ AX, 0(DI)
  wb.go:11		0x44ebe3		488b2c24		MOVQ 0(SP), BP
  wb.go:11		0x44ebe7		4883c408		ADDQ $0x8, SP
  wb.go:11		0x44ebeb		c3			RET
  wb.go:11		0x44ebec		488b442418		MOVQ 0x18(SP), AX
  wb.go:11		0x44ebf1		e83aa1ffff		CALL runtime.gcWriteBarrier(SB)
  wb.go:11		0x44ebf6		ebeb			JMP 0x44ebe3
  wb.go:11		0x44ebf8		e83383ffff		CALL runtime.morestack_noctxt(SB)
  wb.go:11		0x44ebfd		ebb1			JMP main.link(SB)

TEXT main.count(SB) /work/go-p4/wb.go
  wb.go:15		0x44ec00		488b442410		MOVQ 0x10(SP), AX
  wb.go:15		0x44ec05		488b4c2408		MOVQ 0x8(SP), CX
  wb.go:15		0x44ec0a		48894108		MOVQ AX, 0x8(CX)
  wb.go:15		0x44ec0e		c3			RET

count is a single store. link checks a global flag, runtime.writeBarrier, which the collector sets for the duration of marking. When it is clear, the store is a plain MOVQ. When it is set, the store goes through runtime.gcWriteBarrier, which records the old and new pointers in a per-P buffer for the collector. The barrier also turned link from a leaf function, which would need no frame and no stack check, into one with both, because it might make a call. A program pays a compare and a branch on every pointer store all the time, and the real barrier only while a collection is marking.

The rest of a cycle, from the same comment, in short:

  1. Sweep termination: stop the world, finish any sweeping left over from the last cycle.
  2. Mark: turn the write barrier on, start the world again. Background mark workers, which the scheduler gives a quarter of the processors, scan stacks, globals and the heap. Goroutines that allocate during marking are made to help (mark assists), in proportion to how much they allocate, so that a fast allocator cannot outrun the collector. New objects are allocated black.
  3. Mark termination: stop the world again, check there is no work left, turn the barrier off.
  4. Sweep: concurrently, as Part 3 described, in the background and lazily on allocation.

So a cycle stops the world twice, briefly. Everything else runs alongside the program, which is why the pauses are short. Rick Hudson, who led the work, gave the goal in his keynote at the International Symposium on Memory Management last June, published on the Go blog in July: “We now have an objective of 500 microseconds stop the world pause per GC cycle.” The longest pause in every run below was under 0.6 ms.

When the collector runs

A non-generational collector has to trace the whole live heap every cycle, so how often it runs decides what it costs. Go’s answer is a single knob, GOGC, which defaults to 100. After each cycle the collector sets a heap goal: the live heap it just found, plus GOGC percent. With the default, the next cycle is due when the heap has doubled. A program with 512 MB live runs a cycle every 512 MB of allocation. A program with almost nothing live runs one every 4 MB, which is the minimum goal. The pacer then starts each cycle early enough to finish marking just as the heap reaches the goal, using the assist rate and the background workers to keep marking ahead of allocation.

GODEBUG=gctrace=1 makes the runtime print one line per cycle to standard error. The format is documented in src/runtime/extern.go:

	gc # @#s #%: #+#+# ms clock, #+#/#/#+# ms cpu, #->#-># MB, # MB goal, # P
	where the fields are as follows:
		gc #        the GC number, incremented at each GC
		@#s         time in seconds since program start
		#%          percentage of time spent in GC since program start
		#+...+#     wall-clock/CPU times for the phases of the GC
		#->#-># MB  heap size at GC start, at GC end, and live heap
		# MB goal   goal heap size
		# P         number of processors used
	The phases are stop-the-world (STW) sweep termination, concurrent
	mark and scan, and STW mark termination. The CPU times
	for mark/scan are broken down in to assist time (GC performed in
	line with allocation), background GC time, and idle GC time.

Here is one line from the experiment below, a cycle in a program holding 512 MB of objects with pointers in them:

gc 7 @0.349s 7%: 0.005+29+0.30 ms clock, 0.12+0.38/173/459+7.3 ms cpu, 1073->1128->630 MB, 1152 MB goal, 24 P

Read it field by field:

  • gc 7 @0.349s 7%: the seventh cycle, 0.349 seconds after start; 7% of the program’s time so far has gone to collection.
  • 0.005+29+0.30 ms clock: the first stop-the-world phase took 5 microseconds, concurrent marking 29 milliseconds of wall time, and the second stop-the-world phase 0.30 milliseconds. The program was stopped for about a third of a millisecond in all.
  • 0.12+0.38/173/459+7.3 ms cpu: the same phases in CPU time, summed over processors, with marking split three ways: 0.38 ms of assists by the program’s own goroutines, 173 ms by the dedicated background workers, and 459 ms by idle workers, which the scheduler runs on processors that have nothing else to do. This program has one busy goroutine and 24 processors, so most of the marking ran on the other 23 for free.
  • 1073->1128->630 MB: the heap was 1,073 MB when the cycle began, 1,128 MB when marking finished (the program kept allocating during it), and 630 MB of it was found to be live.
  • 1152 MB goal: the goal this cycle was aiming at, 2 × the previous cycle’s live heap.
  • 24 P: GOMAXPROCS.

What the collector’s time follows

That line shows 640 ms of CPU for one cycle. Whether that is a lot depends on what it bought. This program makes the same 3.2 GB of garbage, 50 million 64-byte objects each dropped at once, while holding one of three live heaps of the same size: nothing, 512 MB of arrays with no pointers in them, or 512 MB of objects that each hold one pointer.

package main

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

// node is 64 bytes and holds one pointer, so the collector must scan it.
type node struct {
	next *node
	pad  [7]int64
}

var ptrs []*node   // live set made of 8 million separately allocated nodes
var flat [][]int64 // live set of the same size with no pointers in it
var sink *node

func main() {
	kind := os.Args[1] // none, flat or ptrs
	const liveBytes = 512 << 20
	switch kind {
	case "ptrs":
		ptrs = make([]*node, liveBytes/64)
		for i := range ptrs {
			ptrs[i] = new(node)
		}
	case "flat":
		for i := 0; i < liveBytes>>20; i++ {
			flat = append(flat, make([]int64, 1<<17)) // 1 MB each
		}
	}
	runtime.GC()
	var a, b runtime.MemStats
	runtime.ReadMemStats(&a)
	fmt.Fprintf(os.Stderr, "--- churn starts, live heap %d MB\n", a.HeapAlloc>>20)
	t := time.Now()
	for i := 0; i < 50000000; i++ {
		sink = new(node) // 50 million 64-byte objects: 3.2 GB of garbage
	}
	el := time.Since(t)
	runtime.ReadMemStats(&b)
	fmt.Fprintf(os.Stderr, "--- churn ends\n")
	var maxPause uint64
	for i := a.NumGC; i < b.NumGC; i++ {
		if p := b.PauseNs[i%256]; p > maxPause { // collection i+1 is stored at index i
			maxPause = p
		}
	}
	fmt.Printf("%-4s live %3d MB  churn %5.2f s  GCs %3d  STW total %6.2f ms  longest %5.3f ms\n",
		kind, a.HeapAlloc>>20, el.Seconds(), b.NumGC-a.NumGC,
		float64(b.PauseTotalNs-a.PauseTotalNs)/1e6, float64(maxPause)/1e6)
}

Three runs of each, with GODEBUG=gctrace=1, and a fourth case: the pointer-heavy heap again, with GOGC=400:

$ go build -o gcload gcload.go
$ for k in none flat ptrs; do for r in 1 2 3; do GODEBUG=gctrace=1 ./gcload $k 2> trace-$k-$r.txt; done; done
none live   0 MB  churn  0.76 s  GCs 827  STW total  84.00 ms  longest 0.346 ms
none live   0 MB  churn  0.77 s  GCs 828  STW total  85.82 ms  longest 0.362 ms
none live   0 MB  churn  0.76 s  GCs 827  STW total  80.11 ms  longest 0.312 ms
flat live 512 MB  churn  0.96 s  GCs   6  STW total   1.98 ms  longest 0.417 ms
flat live 512 MB  churn  0.86 s  GCs   6  STW total   2.23 ms  longest 0.573 ms
flat live 512 MB  churn  0.86 s  GCs   6  STW total   1.83 ms  longest 0.436 ms
ptrs live 576 MB  churn  1.05 s  GCs   5  STW total   1.66 ms  longest 0.484 ms
ptrs live 576 MB  churn  1.04 s  GCs   5  STW total   1.95 ms  longest 0.491 ms
ptrs live 576 MB  churn  1.08 s  GCs   5  STW total   1.84 ms  longest 0.455 ms
$ for r in 1 2 3; do GOGC=400 GODEBUG=gctrace=1 ./gcload ptrs 2> trace-ptrs400-$r.txt; done
ptrs live 576 MB  churn  1.15 s  GCs   1  STW total   0.32 ms  longest 0.315 ms
ptrs live 576 MB  churn  1.18 s  GCs   1  STW total   0.30 ms  longest 0.304 ms
ptrs live 576 MB  churn  1.39 s  GCs   1  STW total   0.27 ms  longest 0.265 ms

(The pointer case reports 576 MB live, not 512: the slice holding the 8 million pointers is itself 64 MB.) Summing the CPU fields of every trace line printed during the churn gives the collector’s total work, which the program’s own numbers do not show:

Live heapGOGCCyclesCollector CPUPer cycleMark, wall clock
nothing1008272,018 ms2.4 ms0.07 ms
512 MB, no pointers100652 ms8.6 ms0.42 ms
512 MB of pointers10053,054 ms611 ms28 ms
512 MB of pointers4001648 ms648 ms29 ms

Collector CPU while making 3.2 GB of garbage

Milliseconds of CPU the collector reported, median of three runs, Go 1.11.4, 24 Ps.

nothing else liveGOGC=100 · 827 GCs
2,018 ms
512 MB, no pointersGOGC=100 · 6 GCs
52 ms
512 MB of pointersGOGC=100 · 5 GCs
3,054 ms
512 MB of pointersGOGC=400 · 1 GCs
648 ms

Hover or focus a row for the per-cycle figures.

The garbage is identical in every row. What the collector's time follows is the live heap it has to trace: pointers cost, bytes without pointers do not, and a small heap goal means many cycles. Most of these milliseconds ran on processors the program was not using.

Two things follow at once, and they are the leak this part is about.

The garbage costs nothing to collect. Every row made the same 3.2 GB of it. A collector that only traces what is live never looks at the dead objects. They become free when sweeping finds them unmarked, and sweeping, as Part 3 showed, only reads mark bits.

The live heap costs, but only its pointers. Half a gigabyte of []int64 took 0.4 ms of marking per cycle, because those arrays sit in noscan spans: the collector marks each array as reachable and never looks inside. Half a gigabyte of objects with one pointer each took 28 ms of wall-clock marking per cycle, because the collector had to visit 8 million objects and follow every pointer. The bytes are the same. The work is not. And because the collector is not generational, it does that work on every cycle, whether the objects have changed or not. The 512 MB were created before the churn began and never touched again, and they were traced five times.

The CPU column needs more care than that, because this machine had 23 processors with nothing else to do, and the collector used them. Mark workers run on idle Ps, and starting, feeding and stopping two dozen of them has a cost of its own on every cycle. That is the only way the empty heap can cost two seconds of CPU: its 827 cycles each took 2.4 ms of CPU to do almost nothing, about 0.1 ms of it per processor. The total says as much about the machine as about the work.

When there is no idle processor

So the same three programs ran again with GOMAXPROCS=1: one processor, shared by the program and its collector, with nothing idle to hand work to. Three runs of each:

$ for k in none flat ptrs; do for r in 1 2 3; do GOMAXPROCS=1 GODEBUG=gctrace=1 ./gcload $k 2> trace1p-$k-$r.txt; done; done
none live   0 MB  churn  0.63 s  GCs 769  STW total   1.17 ms  longest 0.204 ms
none live   0 MB  churn  0.63 s  GCs 769  STW total   0.98 ms  longest 0.010 ms
none live   0 MB  churn  0.62 s  GCs 769  STW total   0.89 ms  longest 0.004 ms
flat live 512 MB  churn  0.91 s  GCs   6  STW total   0.03 ms  longest 0.006 ms
flat live 512 MB  churn  0.81 s  GCs   6  STW total   0.03 ms  longest 0.006 ms
flat live 512 MB  churn  0.81 s  GCs   6  STW total   0.03 ms  longest 0.006 ms
ptrs live 576 MB  churn  1.59 s  GCs   3  STW total   0.02 ms  longest 0.007 ms
ptrs live 576 MB  churn  1.61 s  GCs   3  STW total   0.02 ms  longest 0.009 ms
ptrs live 576 MB  churn  1.65 s  GCs   3  STW total   0.03 ms  longest 0.018 ms

Summed from the traces as before, medians of the three runs:

Live heapCyclesCollector CPU, 1 Pof which assistsChurn, 1 PCollector CPU, 24 P
nothing76912 ms12 ms0.63 s2,018 ms
512 MB, no pointers63 ms3 ms0.81 s52 ms
512 MB of pointers3497 ms12 ms1.61 s3,054 ms

On one processor the empty heap’s 769 cycles cost 12 ms in all, not two seconds: almost all of the 24-processor figure was the price of parallel marking on processors that had nothing better to do. The pointer-free heap cost 3 ms. The pointer-heavy heap cost 497 ms, 165 times as much, and now nothing hid it: the program took 1.61 seconds to make its garbage instead of 0.81, twice as long. Half a second of the difference was its only processor tracing 8 million objects it had already traced before.

One cycle from the pointer-heavy run shows something else:

gc 5 @0.609s 29%: 0.001+639+0.004 ms clock, 0.001+7.2/156/0+0.004 ms cpu, 577->1929->1928 MB, 1152 MB goal, 1 P

Marking took 639 ms of wall-clock time, because the single processor gave the collector only a share of its time. Meanwhile the program went on allocating, and every object allocated during marking is black: it survives this cycle whether it is garbage or not. So the heap reached 1,929 MB against a goal of 1,152, and the cycle reported 1,928 MB live, most of it garbage that had been made while marking ran. The next goal is computed from that figure, which is why this run needed only three cycles. Floating garbage like this is the price of marking concurrently: a slow mark lets the heap overshoot, and the overshoot is carried into the next cycle.

A small heap means many cycles. The 4 MB minimum goal gave the empty-heap program 827 cycles on 24 processors and 769 on one. Each is cheap, but each stops the world twice and wakes the workers. GOGC moves the trade-off both ways: at 400, the pointer-heavy program ran one cycle instead of five and spent a fifth of the CPU on collection, in exchange for a heap allowed to grow to five times the live data.

And the stop-the-world pauses were short in every case: under 0.6 ms on 24 processors, under 0.21 ms on one, including the pointer-heavy heap. Concurrency moved the cost of tracing out of the pauses and into CPU time, which is the trade Go’s collector was designed to make.

Why not generations, and why not move

A generational collector would make the pointer-heavy case cheap: young collections would never trace the old 512 MB, and the garbage would die in the young generation. So why does Go not have one? The Go team explained in July, in the published text of Rick Hudson’s keynote, “Getting to Go: The Journey of Go’s Garbage Collector”. Three reasons stand out.

Go is a value-oriented language. “Go is a value-oriented language in the tradition of C-like systems languages”, Hudson said, and “Of course Go can have pointers and in fact they can have interior pointers.” A Go struct holds its fields inline, an array of structs is one block of memory, and a pointer can point into the middle of an object. A Java program of the same shape is a web of separate small objects, which is exactly what generational collection is built for. Go programs make fewer, larger objects.

Escape analysis already takes the young objects. The Go team built and measured a generational collector, and found that “Escape analysis is picking up a lot of those objects and sticking them on the stack”, so “generational collection is much less effective than you might find in other managed runtime languages.” Part 2 of this series showed what that looks like: the short-lived point that HotSpot’s escape analysis removes at run time, Go’s compiler had already put in a stack frame at build time. And the write barrier a generational collector needs on every pointer store, all the time, cost too much: “The write barrier was fast but it simply wasn’t fast enough.”

Moving objects would break cgo. “We have a fast FFI with C and C++”, and a collector that never moves anything never has to worry that a pointer held by C code has gone stale. Part 1 showed the one place Go does move memory, goroutine stacks, and the rule that comes with it: C may not keep a Go pointer. Heap objects can be handed to C during a call exactly because they stay put. Not moving also meant, in Hudson’s words, that “we didn’t have to deal with the long tail of bugs you might encounter if you had a moving collector”. Part 3 showed what it costs instead: size classes, and spans that cannot be freed while one object in them lives.

He described one other experiment, a request-oriented collector that tried to free the memory of each goroutine’s request without tracing the whole heap. It needed its write barrier on all the time, and on the machines of the day “we couldn’t overcome the write barrier tax”: the slowdowns were “30, 40, 50% and more”. Neither experiment shipped. What shipped is the collector measured above.

The same garbage elsewhere

Java 11. The same program in Java (a Node of 64 bytes, as in Go, with one reference and six longs, the same 8 million of them live, the same 50 million made and dropped):

import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;

public class GCLoad {
    // 12-byte header + one 4-byte reference (compressed, with a heap under 32 GB)
    // + six longs = 64 bytes, the size of the Go node.
    static final class Node { Node next; long a, b, c, d, e, f; }

    static Node[] ptrs;   // live set of 8 million separately allocated objects
    static long[][] flat; // live set of the same size with no references
    static Node sink;

    static long[] gcStats() {
        long n = 0, ms = 0;
        for (GarbageCollectorMXBean b : ManagementFactory.getGarbageCollectorMXBeans()) {
            n += b.getCollectionCount();
            ms += b.getCollectionTime();
        }
        return new long[] {n, ms};
    }

    public static void main(String[] args) {
        String kind = args[0];
        final int liveBytes = 512 << 20;
        if (kind.equals("ptrs")) {
            ptrs = new Node[liveBytes / 64];
            for (int i = 0; i < ptrs.length; i++) ptrs[i] = new Node();
        } else if (kind.equals("flat")) {
            flat = new long[liveBytes >> 20][];
            for (int i = 0; i < flat.length; i++) flat[i] = new long[1 << 17];
        }
        System.gc();
        long[] s0 = gcStats();
        long t0 = System.nanoTime();
        for (int i = 0; i < 50_000_000; i++) sink = new Node(); // 50 million short-lived objects
        long t1 = System.nanoTime();
        long[] s1 = gcStats();
        System.out.printf("%-4s churn %5.2f s  collections %4d  time in collections %5d ms%n",
            kind, (t1 - t0) / 1e9, s1[0] - s0[0], s1[1] - s0[1]);
    }
}
$ javac GCLoad.java
$ for gc in G1 Parallel; do for k in none flat ptrs; do java -Xms3g -Xmx3g -XX:+Use${gc}GC -Xlog:gc:file=jgc-$gc-$k.log GCLoad $k; done; done
none churn  0.95 s  collections    2  time in collections     2 ms
flat churn  0.87 s  collections    2  time in collections     2 ms
ptrs churn  0.73 s  collections    8  time in collections     8 ms
none churn  0.47 s  collections    4  time in collections     8 ms
flat churn  0.35 s  collections    4  time in collections    11 ms
ptrs churn  0.37 s  collections    4  time in collections    11 ms
$ grep -o 'Pause [A-Za-z ()-]*' jgc-G1-ptrs.log | sort | uniq -c
      1 Pause Full (System
     11 Pause Young (Normal) (G
$ grep 'Pause Full' jgc-G1-ptrs.log
[0.283s][info][gc] GC(3) Pause Full (System.gc()) 556M->545M(3072M) 62.601ms

(The first three lines are G1, the default collector since Java 9; the last three the older Parallel collector.) Both are generational, and both copy. The logs show that every collection in the churn was a young collection (the one full collection is the System.gc() before it, and the other three young ones in the G1 log happened while the 8 million objects were being built; the 545 MB live after the full collection is the 8 million 64-byte nodes and their 32 MB array): it traced from the roots and from the old objects recorded by the write barrier as pointing into the young generation, copied the few young survivors, and wrote off the rest of the young generation at once. Whether the old generation held 512 MB of pointers or of numbers barely mattered: 2 to 11 milliseconds of collection for 3.2 GB of garbage, about one millisecond for each young collection. (The heap here is a fixed 3 GB, so the young generation was large and collections were few; Java’s count is time in collections, which for these young collections is the time the program was stopped.)

Java 11 also ships ZGC, a concurrent compacting collector, as an experimental option. The OpenJDK 11.0.1 build used here refused it (“Option -XX:+UseZGC not supported”), so it is not measured.

.NET Core 2.1 has a generational collector with three generations, also compacting. The same program in C#:

using System;

class Node { public Node Next; public long A, B, C, D, E, F, G; }

static class Program
{
    static Node[] ptrs;   // live set of 8 million separately allocated objects
    static long[][] flat; // live set of the same size with no references
    static Node sink;

    static void Main(string[] args)
    {
        string kind = args[0];
        const int liveBytes = 512 << 20;
        if (kind == "ptrs") { ptrs = new Node[liveBytes / 64]; for (int i = 0; i < ptrs.Length; i++) ptrs[i] = new Node(); }
        else if (kind == "flat") { flat = new long[liveBytes >> 20][]; for (int i = 0; i < flat.Length; i++) flat[i] = new long[1 << 17]; }
        GC.Collect();
        int g0 = GC.CollectionCount(0), g1 = GC.CollectionCount(1), g2 = GC.CollectionCount(2);
        var sw = System.Diagnostics.Stopwatch.StartNew();
        for (int i = 0; i < 50_000_000; i++) sink = new Node(); // 50 million short-lived objects
        sw.Stop();
        Console.WriteLine($"{kind,-4} churn {sw.Elapsed.TotalSeconds,5:F2} s  gen0 {GC.CollectionCount(0) - g0,4}  gen1 {GC.CollectionCount(1) - g1,3}  gen2 {GC.CollectionCount(2) - g2,3}");
    }
}
$ for k in none flat ptrs; do dotnet bin/Release/netcoreapp2.1/gcload.dll $k; done
none churn  0.23 s  gen0  635  gen1   0  gen2   0
flat churn  0.24 s  gen0  635  gen1   0  gen2   0
ptrs churn  0.24 s  gen0  635  gen1   1  gen2   0

635 young-generation collections, each over a small generation 0 that was almost entirely garbage, and the whole churn in a quarter of a second, whatever the old generation held. The 512 MB were never traced again after they were promoted.

CPython counts references: an object is freed the moment its last reference goes, with no tracing at all for ordinary garbage, and a separate cycle collector, itself generational, for the cycles that counting cannot see. The Python series on this site covered it in detail. Erlang gives every process its own heap, collected by copying, separately from every other process, so a collection pauses one process for as long as its own heap takes. C++ and Rust have no collector: memory is freed when its owner goes out of scope, and the cost of freeing is paid at that moment, by the code that owned it.

Reading a trace of your own program

The experiments above suggest what to look for when GODEBUG=gctrace=1 is turned on in a real program.

How often, and how much is live. The time between cycles (@#s) and the live heap (the third number of #->#-># MB) say how hard the program is pushing the collector. Cycles a few milliseconds apart with a live heap of a few megabytes mean the 4 MB minimum goal is setting the pace, and the program pays the fixed cost of a cycle hundreds of times a second.

Where the marking happened. The middle of the CPU field splits marking into assists, background work and idle work. Idle work is free only while the machine really has idle processors. Assist time is the important one: it is marking done by the program’s own goroutines, inside their allocations, because they were allocating faster than the background workers could mark. A large assist figure means the collector is taking its time directly out of the program’s requests.

Whether the goal held. The first two heap figures against the goal show whether marking kept up. In the one-processor run, 577->1929 against a goal of 1,152 MB meant marking was too slow for the allocation rate, and the overshoot became floating garbage that was carried into the next cycle’s goal.

The pauses. The first and third clock figures are the stops of the world. In every run here they were well under a millisecond. If a program’s are not, the cause is usually a goroutine that cannot be stopped quickly, such as one in a long loop that makes no function calls. Part 1 showed why: a goroutine is asked to stop through the stack check at the top of a function, so a loop that calls nothing never sees the request, and the whole world waits for it.

What this means for Go code

Count the pointers, not the bytes. The collector’s work per cycle follows the number of live objects and pointers. A map[string]*Record of ten million entries is ten million objects to trace, plus their strings; a slice of structs with no pointer fields is one object the collector does not look into. Indices into a slice instead of pointers, [N]byte instead of string for fixed-size keys, and values instead of pointers in big tables all cut the tracing.

The whole live heap is traced every cycle. There is no old generation that is left alone. Data that is loaded once and kept for the life of the process, a cache or an index, is paid for again in every cycle, for as long as it lives.

GOGC trades memory for CPU. Raising it means fewer cycles over the same live heap, and a bigger peak heap. A program with very little live data runs many cheap cycles at the 4 MB minimum goal, which can add up to real CPU.

Pauses are not the problem they were. Every pause measured here was under 0.6 ms, with half a gigabyte of pointers live. The cost of Go’s collector is in CPU time and in the memory headroom the heap goal needs, not in the program stopping.

A note on the evidence

What ran. Go 1.11.4 (go1.11.4.linux-amd64.tar.gz, checked against its published SHA-256), released on 14 December 2018, on an Ubuntu 18.04 userland as released, in a chroot on a 24-thread x86-64 machine under the host’s Linux kernel. Java is OpenJDK 11.0.1+13, the AdoptOpenJDK build of 16 October 2018 (SHA-256 verified). .NET Core is the 2.1.300 SDK with runtime 2.1.0, with concurrent workstation collection, the default for a console program.

What was measured. Every Go case ran three times in one sitting with nothing else running; the table gives medians, and every run’s output is above. Collector CPU is the sum of the five CPU figures of every gctrace line printed between the program’s two markers. The Java and .NET programs ran once per case and collector (the Java run shown is a rerun with logging, after the node was trimmed from 72 to 64 bytes to match Go’s; the first runs, with the larger node, gave similar counts and 3 to 24 ms); their counts are what matters here, and the timings show only the order of magnitude. The write-barrier listing is the disassembly of the binary as built.

What changed in the writing. The first version of gcload.go read the pause of each collection from the wrong slot of PauseNs (the runtime stores collection n at index n − 1), so its “longest” column was off by one collection. The program above is the corrected one, and every Go number here is from a rerun of it; the totals, which come from PauseTotalNs, were the same both times.

What is quoted. Runtime source and documentation are from the go1.11.4 tag (mgc.go, mbarrier.go, extern.go); Go 1.8’s release note from doc/go1.8.html. Rick Hudson’s words are from “Getting to Go: The Journey of Go’s Garbage Collector”, the Go blog, 12 July 2018, the text of his ISMM keynote of 18 June 2018.

More