go-benchmarks · benchmark 001 · Go 1.27.1 · i7-6700 · GOMAXPROCS=8

What a pointer costs

The same 10M records in a Go service's memory can cost the garbage collector about a millisecond per cycle, or almost a second. The only difference is how the data is stored: whether their types contain pointers or not. This page explains why that happens and how to store long-lived data so the collector has less work to do. First some context, then examples, what to do and how to check your own service, with charts at the end. Unfamiliar terms are collected in the glossary at the bottom of the page.

Some context

How the garbage collector finds live objects

Everything the program creates via new, make, &T{}, slices, strings and maps usually lives on the heap. In Go you don't free this memory by hand: from time to time the garbage collector (GC) runs and finds out on its own what is still in use.

It does so like this. It takes the roots: global variables and variables on goroutine stacks. From them it follows every pointer, marks the object it reached as live, and then looks at that object's pointer fields. This is called marking (mark/scan). Everything the collector did not reach is considered garbage and is freed.

Hence the main point: marking work grows with the number of live objects and the pointers between them. If a type has no pointers at all, the collector marks such an object as live and does not look inside (such objects are called noscan).

When a collection starts. Usually when the heap has grown (this is governed by GOGC). But there is also a timer-triggered GC: if there has been no collection for two minutes, the runtime starts one itself. A service that hardly creates any new objects gets only such collections.

What an LRU cache is

A cache stores results that are expensive to obtain again, for example database responses. Memory is not infinite, so the cache has a limit, and when it is full something has to be thrown out. LRU (least recently used) evicts the entry that has gone unused the longest.

A classic Go implementation: a map from key to node plus a doubly linked list of nodes. On every access the node is moved to the head of the list, and the node at the tail is evicted:

type entry struct {
	key        string     // the key, so the entry can be deleted from the map on eviction
	value      *ReadState // the data itself
	prev, next *entry     // neighbors in the list
}

cache := map[string]*entry{}

Convenient and fast, but each entry carries several pointers: from the map to the node, from the node to its neighbors, to the data and to the key bytes.

The discord case

In 2020 discord rewrote the Read States service from Go to Rust. The service kept an LRU cache of millions of entries in memory and created almost nothing anew. So collections came to it only from the timer, once every two minutes, and each one walked the entire cache. On the graphs this showed up as a CPU and response latency spike every two minutes.

The timer is still in the Go runtime. I checked the same mechanics on Go 1.27.1.

Four examples and why they are the way they are

All examples hold the same 10M ReadState records: two numeric fields, 16 bytes, no pointers.

type ReadState struct {
	LastReadID   uint64
	MentionCount uint32
}

Only the storage method changes. Each following example removes one more source of pointers, so that you can see what each of them costs:

Example How it is stored What changed and why Pointers per record Objects on the heap
A · LRU as in discord map[string]*entry + doubly linked list Starting point: reproduces the discord case 6 25M
P · map of pointers map[uint64]*ReadState Removed the list and the string key, but the record still lives behind a pointer. The most common way to keep data in memory: a map-based "repository". The question: what does a single * per record cost 1 10M
B2 · string key map[string]ReadState Removed the *, the record lies directly in the map, but the key is still a string. The question: if there is not a single * in the code, does that mean there are no pointers 1, in the key 5M
B · flat map map[uint64]ReadState Not a single pointer. Lower bound: what a collection costs when there is no need to look inside 0 33K

The data is deliberately identical: this way the difference in cost is explained only by the storage method, not by volume. B2 has half as many objects as keys: the runtime puts the bytes of two short strings into one block, this is done by the tiny allocator. P and B also weigh almost the same (441 and 426 MB), so they show well that the collector does not pay per megabyte.

Conditions: a synthetic cache without requests and without eviction, filled once, after which the program does nothing for 11 minutes, and only timer-triggered collections count. i7-6700, Linux, GOMAXPROCS=8, three runs per example.

×812
times shorter marking of the flat map than of the Discord-style LRU, with the same 10M entries
974 ms
the LRU marking takes every 121–122 s even when fully idle, on two of eight logical CPUs
0.06 ms
longest STW pause across all timer-triggered GCs. The rest of the cycle runs alongside the program
40–200 ns
CPU per live object per GC in this benchmark, across examples and modes. A million long-lived objects costs about 100 ms per GC here

What the numbers mean. Mark/scan wall-clock time: how long background marking lasts, while the program keeps running. Mark CPU: how much CPU time marking consumed in total across all cores. STW: how long the program actually stood still, here no more than 0.06 ms per collection. Live heap: how much memory is in use after marking. The other phases of a collection are short, so below "collection" almost everywhere means its marking.

What to do

This applies only to data that lives long and exists in millions of instances: caches, in-memory indexes, reference tables. Temporary objects created for a single request are already dead by the time of a collection, and the collector does not walk them. The effect below was measured on a timer-triggered GC at 10M records (median mark/scan wall-clock time).

Number as key, record as value

map[string]*Entry → map[uint64]Entry

The string key becomes a unique numeric id, and the record is stored as a value with no pointers inside. A string hash instead of an id is suitable only if collisions are ruled out or handled. In the benchmark, "before" corresponds to the LRU as in discord: such a map plus a doubly linked list. Effect: 974 ms → 1.2 ms per collection.

Value instead of pointer

map[K]*T, []*T → map[K]T, []T

One object and one pointer fewer per record. It works if T is small, has no pointers itself, and the record does not need a separate identity: nobody holds a *T, and the record is replaced as a whole via m[k] = v. Cost: T is copied on every read and update, which is expensive for a large T. Effect: 515 ms → 1.2 ms per collection.

Key without a string

map[string]T → map[uint64]T

A string holds a pointer to its bytes. A single string key is enough for the collector to walk the entire map, even if the values have no pointers. Effect: 364 ms → 1.2 ms per collection.

Fields without hidden pointers

// before
CreatedAt time.Time
ID        string
Meta      any
// after
CreatedAt int64
ID        [16]byte
Meta      Meta

time.Time hides a *Location, and string and any also contain pointers. One such field makes the whole struct scannable. int64 (Unix time in nanoseconds) is suitable if you only need a point in time: the time zone and the monotonic clock are lost. Not benchmarked separately, the mechanism is the same.

prev, next *entry → prev, next int32 // indexes into []entry

Lists and trees (an LRU is also a list) can be kept in a single slice of nodes, and instead of pointers to neighbors you store their positions in that slice. In the benchmarked LRU, prev and next account for 2 of the 6 pointers per record. Cost: you have to manage freed slots yourself, for example with a free list. Not benchmarked separately.

Strings in one buffer

[]string → buf []byte and span []struct{ off, n uint32 }

The bytes of all strings lie in one []byte, and the record stores an offset and a length. This is how bigcache and freecache are built. Cost: deleted strings leave holes, and the buffer has to be compacted. Not benchmarked separately.

What does not help. Ordinary GOGC and GOMEMLIMIT values change how often a collection comes because of heap growth. They do not cancel the timer-triggered GC every two minutes, and each such collection walks all live objects. GOGC=off turns off the timer too. If GOMEMLIMIT is set at the same time, collections come when the heap reaches the limit; without a limit the heap grows with no collections at all. This is from the runtime code and the GC guide, not benchmarked separately.

How to estimate the cost in your own service

In this benchmark, the cost of marking was best explained by the number of live objects: on the i7-6700 it came to about 100 ns CPU per object. This is a figure for my hardware and my structs (at 10M records across examples and modes it came to 40–200 ns), not a Go constant. The cost is also affected by the size of the scanned part of an object and how objects are scattered across memory, and on another CPU the figure will be different. As a rough estimate: a million long-lived objects on the i7-6700 cost on the order of 100 ms CPU per collection.

1. How many objects live on the heap. A metric from the standard library runtime/metrics:

s := []metrics.Sample{{Name: "/gc/heap/objects:objects"}}
metrics.Read(s) // import "runtime/metrics"
n := s[0].Value.Uint64()
fmt.Printf("~%v CPU per GC\n", time.Duration(n)*100) // ~100 ns per object

2. Where they were created. A heap profile by the number of live objects; top will show the functions that created the most live objects. The profile will not show who retains them, that is found from the code:

go tool pprof -sample_index=inuse_objects http://localhost:6060/debug/pprof/heap

3. How long a collection actually lasts. Run the service with GODEBUG=gctrace=1: the runtime will print a line for each collection. The second term in ms clock shows mark/scan wall-clock time.

4. Whether a timer-triggered collection came. Before such a collection gctrace prints a GC forced line:

GODEBUG=gctrace=1 ./app 2>&1 | grep -A1 "GC forced"
gc 15 @128.984s 0%: 0.047+1001+0.004 ms clock, ...

One collection, four examples

Median mark/scan wall-clock time for timer-triggered collections at full idle. The data is identical, only the number of pointers per record changes. In parentheses is the spread across 12 collections. The scale is logarithmic; on a linear one the flat map is not visible at all.

The cost is explained by the number of objects

20 runs with runtime.GC() from 100K to 10M records, one per point, so this is an observation on a single workload, no law can be derived from it. By memory volume the points are spread over three orders of magnitude: the flat map at 426 MB costs 1.4 ms CPU, the map of pointers at 441 MB costs 1.1 s. By number of objects all examples lie close to a single line.

by live heap, MB
by number of heap objects

The discord case: a collection every two minutes

The program fills the cache and does nothing for 11 minutes. Collections still come every two minutes, and each time the LRU occupies two logical CPUs out of eight for about a second: for marking the runtime allocates background mark workers at 25% of GOMAXPROCS. Under load this second would share CPU with requests, and goroutines that create objects at that time could be subject to mark assist and help with marking themselves.

A · LRU like Discord'sP · map of pointersB2 · string keyB · flat map

Where pointers hide in Go

The collector goes inside an object if its type has at least one pointer field. A type without pointers (numbers, bool, arrays of them, structs of such fields) it skips entirely.

Type Pointers What is inside
int, float64, bool, [16]byte no Numbers and arrays of numbers. The collector will mark the object live and will not go inside.
struct{ ID uint64; N uint32 } no A struct of numbers is also noscan. This is exactly how ReadState lies in the flat map.
string yes A pointer to the bytes plus a length. A map[string]T key makes the collector walk the entire map: at idle it is about 300 times more expensive than map[uint64]T with the same values.
[]T yes A pointer to an array, a length and a capacity. A slice of numbers: one pointer to the slice, the array itself is noscan.
*T, map, chan, func yes Each of them is a pointer. map[K]V is scanned only if K or V contain pointers.
interface{}, any, error yes Two words: a type and a pointer to the value. An any field in a struct makes it scannable.
time.Time yes Inside is loc *Location. A struct with a time.Time field is no longer noscan. For a cache you can store Unix time in an int64 if you do not need the time zone and monotonic time.
struct with one pointer yes A single pointer field is enough for the collector to read the whole object and follow the reference.
Details: methodology and all numbers

How I benchmarked

Two modes. Timer: 10M records, 11 minutes of idle with no allocations, collections are triggered only by the runtime timer (forcegcperiod); three runs per example. runtime.GC(): 8 calls in a row at sizes from 100K to 10M, one run per configuration. Figures from GODEBUG=gctrace=1, the first collection after filling does not count. All on the default collector in Go 1.27.1, the same one any go build gets.

The interval between collections equals 120 s plus the duration of the previous collection: the runtime counts two minutes from its end.

ConfigurationRunsGCs countedInterval, s (min…max)mark/scan wall clock, ms (median / max)mark CPU, ms (median / max)STW max, msLive heap, MBMax RSS, MB
A · LRU like Discord's312121…122974 / 1,2971,949 / 2,5940.0581,1131,378
P · map of pointers312121…121515 / 5501,030 / 1,1010.038441544
B2 · string key312120…122364 / 389728 / 7780.05716842
B · flat map312120…1201.2 / 2.91.3 / 2.20.049426527

Growth with cache size

runtime.GC() calls, marking CPU, one run per point. For the examples with pointers the cost grows with the number of records, for the flat map it barely changes.

A · LRU like Discord's · map[string]*entry, 6 pointers and 3 objects per entryP · map of pointers · map[uint64]*ReadState, 1 pointerB2 · string key · map[string]ReadState, 1 pointer in the keyB · flat map · map[uint64]ReadState, 0 pointers

All configurations

VariantModeEntriesGCsmark/scan wall clock, msmark CPU, ms (median)min…maxObjectsLive heap, MBns CPU / object
A · LRU like Discord'stimer10M129741,9491,704…2,59425M1,11378
P · map of pointerstimer10M125151,0301,015…1,10110M441103
B2 · string keytimer10M12364728692…7785M716145
B · flat maptimer10M121.21.31.2…2.233K42639
A · LRU like Discord'sruntime.GC()100K73.114.713.6…16.4233K1063
A · LRU like Discord'sruntime.GC()300K77.95856…59734K3379
A · LRU like Discord'sruntime.GC()1M733262257…2752.5M121105
A · LRU like Discord'sruntime.GC()3M7107851843…9047.5M312114
A · LRU like Discord'sruntime.GC()10M73823,0282,951…3,15625M1,113121
P · map of pointersruntime.GC()100K70.95.24.8…5.5100K352
P · map of pointersruntime.GC()300K7213.913…14.7301K1346
P · map of pointersruntime.GC()1M774847…491M5148
P · map of pointersruntime.GC()3M735261257…2773M11887
P · map of pointersruntime.GC()10M71501,1141,101…1,15310M441111
B2 · string keyruntime.GC()100K70.783.83.6…4.133K5116
B2 · string keyruntime.GC()300K7213.112.8…14.1134K2298
B2 · string keyruntime.GC()1M76.44543…47487K8792
B2 · string keyruntime.GC()3M725191189…1941.5M182128
B2 · string keyruntime.GC()10M71341,014992…1,0595M716202
B · flat mapruntime.GC()100K70.130.230.1…0.44523509
B · flat mapruntime.GC()300K70.150.280.2…0.51K13230
B · flat mapruntime.GC()1M70.260.430.3…0.74K53100
B · flat mapruntime.GC()3M70.410.540.4…0.78K10664
B · flat mapruntime.GC()10M71.21.371.1…1.933K42642

Glossary