Post

Go Generics and GC Shapes: When a Generic Call Costs 3.5x, Measured

A generic Go max over 16-byte structs took 3.5x the cycles of a hand-written loop when it called a method, and 1.0x with a func. Measured with objdump, pprof.

Go Generics and GC Shapes: When a Generic Call Costs 3.5x, Measured

Go generics are often explained like this: “Go generics are like C++ templates, so a generic function is as fast as the hand-written one.” That is half true. Whether it holds for your code depends on something you never see in the source: the GC shape of the type argument, and whether the compiler can see the call it has to make.

We wrote one small function, “find the record with the largest key”, eight ways and measured each one on the same 4,096 records:

  • a hand-written loop over []Rec
  • generic functions that compare through a method of the type parameter
  • generic functions that compare through a func argument
  • the pre-generics version, a slice of interface values

The generic versions ranged from as fast as hand-written code to 3.5 times slower, and the difference came from one choice: method or func.

The same split shows up in the standard library’s sort functions, which this post also measures. The program, the scripts and every number here are in this blog’s repository under scripts/go-generics-shapes/.

How Go compiles a generic function

Go does not create a full copy of a generic function for every type argument, and it does not box everything like Java either. It uses GC shape stenciling with dictionaries:

  • Type arguments that look the same to the garbage collector and the register allocator share one compiled copy, called a shape. uint64 is its own shape. A struct {Key uint64; ID uint32; Score float32} is its own shape. Every pointer type is the same shape, go.shape.*uint8, whatever it points to.
  • Each shape’s code gets a hidden extra argument, the dictionary. It holds what differs between the types that share the shape, such as type descriptors and the addresses of the methods the constraint requires.

So when a generic body calls x.Less(y) on a type parameter, the shape’s code does not know which Less to call. It loads the method’s address from the dictionary and makes an indirect call. This happens even when only one type ever uses that shape, as in our program.

A comparison passed in as a func value is a different case. If the generic function is small enough to inline, the compiler copies its body into the caller, sees the func literal right there, and inlines that too.

The workload

gshape is a small Go program that uses the standard library only. The record is 16 bytes:

1
2
3
4
5
6
7
type Rec struct {
	Key   uint64
	ID    uint32
	Score float32
}

func (r Rec) Less(o Rec) bool { return r.Key < o.Key }

The generic helpers live in their own package rec, the way a generic helper usually comes from a library. Here are the two main ones:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Constraint with a method: the comparison is part of T.
func MaxBy[T Lesser[T]](xs []T) T {
	best := xs[0]
	for _, x := range xs[1:] {
		if best.Less(x) {
			best = x
		}
	}
	return best
}

// Comparison passed as a func, the shape of slices.MaxFunc and slices.SortFunc.
func MaxFunc[T any](xs []T, less func(a, b T) bool) T {
	best := xs[0]
	for _, x := range xs[1:] {
		if less(best, x) {
			best = x
		}
	}
	return best
}

Each run scans 4,096 records (64 KiB, small enough to stay in the core’s L1 data cache) 50,000 times. The data comes from a seeded generator, so every variant sees the same keys. Every variant must print the same checksum, or summarise.py refuses the run.

variantwhat it is
concretethe hand-written loop over []Rec
gen-funcMaxFunc[Rec] with func(a, b Rec) bool { return a.Key < b.Key }
gen-keyMaxKey[Rec, uint64] with a key func and cmp.Ordered keys
gen-methodMaxBy[Rec], which calls the Less method
gen-func-noinlMaxFunc marked //go:noinline, like a generic function that is too big to inline
gen-lessofa hand-written loop that calls the one-line generic LessOf[T Lesser[T]](a, b T) bool
iface[]LessI interface values, the pre-generics way
*-ptrthe same over []*Rec, pointing into one contiguous array
*-u64the same scan over the bare []uint64 keys

How we measured

All runs used one Apple M2 Pro (8 performance and 4 efficiency cores, macOS 27.0.1) and go1.27.4 darwin/arm64. measure.sh runs each cell as a separate process under /usr/bin/time -l, which reports instructions retired and cycles elapsed for that process. It runs all 25 cells in a shuffled order, 11 times over. From each count it subtracts a none cell that builds the same data and does no work, and divides by the number of elements.

The host was busy during the runs: the 1-minute load average was between 13.6 and 17.8. Wall time per element changed 2.0x to 3.7x between runs of the same cell, depending on what else was running. Cycles per element did not change much: every scan run was within 10% of its cell’s median, and 204 of the 242 measured runs (84%) were within 4%. The noisiest cell, the 1,000-key uint64 sort, varied by up to 20%, because each of its sorts is short. So we compare cycles, and give wall time only as a rough guide.

Result 1: a method call through the dictionary costs 3.5x

Bar chart of CPU cycles per element for the find-the-max scan over 4,096 elements, median of 11 runs, with instructions per element in brackets. 16-byte struct values: hand-written loop 2.06 cycles [8 instructions], MaxFunc with a func literal 2.07 [9], MaxKey with a key func 2.16 [9], MaxBy calling the Less method 7.24 [33], MaxFunc not inlined 7.24 [32], inlined LessOf 8.10 [42], interface values 9.11 [36]. Pointers: hand-written 1.61 [11], MaxFunc 1.58 [11], MaxByP 7.78 [24]. Basic type uint64: hand-written 2.05 [6], MaxOrdered 2.04 [6]. Every run is within 10% of its row's median; wall time varied 2.0x to 3.7x.

variant (16-byte Rec values)cycles / elementinstructions / elementvs hand-written
hand-written loop2.068.01.00x
MaxFunc[Rec] + func literal2.079.01.01x
MaxKey[Rec, uint64] + key func2.169.01.05x
MaxBy[Rec], Less method7.2433.13.51x
MaxFunc, not inlined7.2432.13.51x
LessOf[Rec], inlined, method8.1042.13.93x
[]LessI interface values9.1136.14.42x

Three things stand out:

  1. Generic code with a func argument cost the same as hand-written code (2.07 against 2.06 cycles per element). This is the “generics are free” case. It holds here because MaxFunc inlined.
  2. The same generic loop with a method constraint took 3.5 times the cycles. MaxBy[Rec] is no longer than MaxFunc, but it ran 33 instructions per element against 9.
  3. An inlined generic that calls a method is still slow. LessOf is a single line: return a.Less(b). The compiler inlined it into the loop, and it was still the slowest generic version, at 3.9x. Inlining the generic function does not remove the dictionary call.

The pre-generics interface version was slowest overall at 4.4x. A generic with a method constraint (3.5x) is only a little faster than an interface. Here generics did not remove the indirect call. They only made it a little cheaper.

What the compiler made

go tool nm lists the generic code in the binary, and go build -gcflags=-m=2 explains each inlining decision:

Terminal panel titled "what the compiler made: shapes and inlining". go tool nm lists three generic functions left in the binary: rec.MaxBy for the struct shape, rec.MaxByP for go.shape.*uint8, and rec.MaxFuncNoInline for the struct shape. Then selected go build -gcflags=-m=2 lines: cannot inline rec.MaxBy for the struct shape, cost 86 exceeds budget 80; cannot inline rec.MaxByP for go.shape.*uint8, cost 86 exceeds budget 80; can inline rec.MaxFunc for the struct shape with cost 42; inlining call to rec.MaxFunc; can inline rec.LessOf for the struct shape with cost 66; inlining call to rec.LessOf.

The names show the mechanism:

  • MaxBy[go.shape.struct { Key uint64; ID uint32; Score float32 }] is compiled code for a shape, not for Rec. Any other struct with the same field layout would share it. Its inline cost is 86, just over the budget of 80, because the method call through the dictionary costs more nodes than a direct comparison. So it stays a real function.
  • MaxByP[go.shape.*uint8] is the pointer version. Every pointer type shares this one body.
  • MaxFunc and LessOf do not appear in the binary as functions. MaxFunc costs 42 and LessOf 66, so both inlined into main.runScan at every call site. For MaxFunc the func literal inlined with it. For LessOf, as the assembly below shows, the Less method it calls did not.

The loop in assembly

go tool objdump shows the difference directly. On the left is the loop of MaxBy’s shape function. On the right is the loop the compiler built from MaxFunc and the func literal inside main.runScan:

Two columns of arm64 assembly from go tool objdump, go1.27.4. Left, titled rec.MaxBy for the struct shape, Less via dictionary: the loop as objdump prints it, 27 instructions with one indirect CALL. It spills the current element's fields to the stack, loads Less's address from the dictionary with MOVD (R0), R4, then calls CALL (R4) for every element, and reloads the fields after the call. Right, titled MaxFunc of Rec inlined into runScan with the func literal inlined: the whole loop is 9 instructions with no call: load the key, CMP, CSEL to keep the larger, advance the pointer by 16, count down, branch.

The inlined loop is nine instructions with no branch for the comparison: a load, a CMP, and a CSEL (conditional select) that keeps the larger key. The MaxBy loop spills the element to the stack, loads Less’s address from the dictionary (MOVD (R0), R4), calls it (CALL (R4)), and reloads the element after the call. The extra cycles in the chart come from that call and the stack traffic around it.

The inlined LessOf shows that this is not about inlining budgets alone. In main.runScan the compiler even turned the dictionary load into a constant: it puts the address of rec.Rec.Less in a register with ADRP/ADD (the symbol table confirms the address). It still does CALL (R4) instead of inlining a three-instruction method. In go1.27.4, a method call on a type parameter stays a call, even when the compiler knows exactly which method it is.

Pointers: one shape for every pointer type

With []*Rec the gap was larger:

variant ([]*Rec)cycles / elementinstructions / elementvs hand-written
hand-written loop1.6111.01.00x
MaxFunc[*Rec] + func literal1.5811.00.98x
MaxByP[*Rec], PLess method7.7824.14.84x

All pointer types share go.shape.*uint8, so a generic method call on a pointer type argument always goes through the dictionary. Here the method call cost 4.8x, while the func version cost the same as hand-written code. (The pointer loops are faster than the value loops in this test because they only load an 8-byte pointer and a key, and the records are contiguous in memory. Over records scattered across the heap, cache misses would dominate.)

For basic types, the generic version is free. MaxOrdered[uint64] with cmp.Ordered ran 2.04 cycles against 2.05 for the hand-written loop, with 6 instructions per element each. uint64 has its own shape, and > on it is one machine instruction.

pprof agrees

The CPU profiles of the two scans tell the same story without reading assembly:

Two pprof flame graphs from go tool pprof -http. Top, MaxBy of Rec with the Less method through the dictionary: 660 ms of samples, main.runScan calls rec.MaxBy for the struct shape, which has a separate rec.Rec.Less frame above it. Bottom, MaxFunc of Rec with a func literal, inlined into main.runScan: 180 ms of samples for the same work, with the MaxFunc frame marked as inlined and nothing above it.

In the MaxBy profile, rec.Rec.Less is a real frame with its own samples (12% flat), because it is a real call. In the MaxFunc profile there is no comparison frame, and pprof marks MaxFunc[go.shape...] as (inline). The same work took 660 ms of samples against 180 ms. In a production profile, a Less, Compare or Hash method showing up as its own frame under a go.shape function is a hint that you are paying for dictionary calls.

Result 2: sorting, where the standard library already chose func

The same rule explains the standard library’s sort APIs. We sorted 16-byte records by key with each of them, at 1,000 and at 100,000 elements:

Bar chart of cycles per element per sort for 16-byte records, median of 11 runs, relative to slices.SortFunc on []Rec. At n = 1,000: slices.SortFunc on []Rec 150.99 (1.00x), slices.SortFunc on []*Rec 148.16 (0.98x), sort.Sort with sort.Interface 150.64 (1.00x), sort.Slice with a less closure 252.65 (1.67x), slices.Sort on bare uint64 keys 38.01 (0.25x). At n = 100,000: slices.SortFunc 302.83 (1.00x), on []*Rec 325.44 (1.07x), sort.Sort 344.14 (1.14x), sort.Slice 457.42 (1.51x), slices.Sort on keys 184.88 (0.61x).

sort callcycles / element, n=1,000n=100,000instructions, n=100,000
slices.SortFunc([]Rec, cmp.Compare on Key)151 (1.00x)303 (1.00x)691
slices.SortFunc([]*Rec, ...)148 (0.98x)325 (1.07x)617
sort.Sort(byKey) (sort.Interface)151 (1.00x)344 (1.14x)801
sort.Slice(xs, less)253 (1.67x)457 (1.51x)1,452
slices.Sort([]uint64) (keys only)38 (0.25x)185 (0.61x)271
  • sort.Slice is the slow one. It took 1.5-1.7x the cycles of slices.SortFunc and ran 2.1x the instructions. It does not know the element type, so it swaps through reflection.
  • slices.SortFunc takes a func, not a method. Its comparison is a func value, just like MaxFunc. sort.Sort took 1.14x its cycles at 100,000 elements and the same at 1,000. A sort is much too large to inline, so the comparison is still an indirect call per comparison in both, and the generic version wins less here than in the scan.
  • Sorting the bare keys is 1.6-4x cheaper. slices.Sort on []uint64 compares with one instruction and moves 8 bytes instead of 16.

pprof shows where sort.Slice’s extra time goes:

pprof flame graph of sort.Slice on 100,000 records, 550 ms of samples. Under main.runSort and sort.Slice, a deep tower of sort.pdqsort_func calls sort.partition_func and insertionSort_func. Many narrow frames on top are internal/reflectlite.Swapper.func9 and typedmemmove, the reflection-based swap, next to main.runSort.func1, the less closure.

In the -top view of the same profile, internal/reflectlite.Swapper.func9 with its typedmemmove calls holds 29% of samples cumulatively. The slices.SortFunc profile has no reflection at all. Its biggest frame is the inlined cmp.Compare[go.shape.uint64], and it swaps with plain moves.

What to do with this

  • In hot generic code, take the comparison (or hash, or key) as a func argument, not as a method in the constraint. That is the slices.SortFunc/slices.MaxFunc design. When the generic function inlines, a func literal inlines with it. A method call on a type parameter did not, even when the function inlined (LessOf).
  • Keep hot generic functions small enough to inline. MaxFunc cost 42 against a budget of 80. The same MaxFunc with inlining switched off was as slow as the method version (7.24 cycles). Check with go build -gcflags=-m=2 2>&1 | grep 'inline.*go.shape'.
  • Generic code over basic types (cmp.Ordered) is as fast as hand-written code. Each basic type gets its own shape, and the operators are machine instructions.
  • Be most careful with pointer type arguments. Every pointer is one shape, so method calls on them always go through the dictionary. That cost 4.8x here.
  • Replace sort.Slice with slices.SortFunc. It cost 1.5-1.7x the cycles here, and the change is mechanical.
  • Measure cycles or instructions, not wall time, on a shared machine. Our wall times moved 2-3.7x between runs, while 84% of runs stayed within 4% on cycles. A 1.05x difference in wall time would have been noise. /usr/bin/time -l on macOS and perf stat -e cycles,instructions on Linux both give these counts.

None of this is a reason to avoid generics. The fastest generic code here was exactly as fast as the hand-written code. It is a reason to know which shape your type arguments have, and to read -gcflags=-m once before you put a generic helper in a hot loop.

Reproduce it

1
2
3
4
bash scripts/go-generics-shapes/measure.sh /tmp/gs-work           # ~2.5 min: 11 reps x 25 cells, objdump, -m=2
python3 scripts/go-generics-shapes/summarise.py /tmp/gs-work      # -> scripts/data/go-generics-shapes-m2pro.json
BROWSER_PATH=<chrome-headless-shell> bash scripts/go-generics-shapes/shots.sh /tmp/gs-work
python3 scripts/go-generics-shapes/gen_images.py /tmp/gs-work     # charts, compiler and asm panels, pprof screenshots

The program needs only the Go standard library. measure.sh uses macOS’s /usr/bin/time -l for the counters. On Linux, replace it with perf stat -e cycles,instructions. On amd64 the assembly looks different, but the dictionary call does not depend on the architecture, so the method versus func result should be the same.

Takeaways

  • A generic method call costs the same everywhere a type parameter is involved. MaxBy[Rec] took 3.5x the cycles of a hand-written loop, MaxByP[*Rec] 4.8x, and an inlined one-line LessOf 3.9x. Each one had an indirect CALL through the dictionary for every element.
  • A generic func argument that inlines costs nothing. MaxFunc[Rec] cost 1.01x and MaxFunc[*Rec] 0.98x the cycles of the hand-written loop. The compiler reduced the loop to nine instructions, the same as hand-written code.
  • Inlining is required for that. The same MaxFunc without inlining cost 3.5x.
  • sort.Slice costs 1.5-1.7x the cycles of slices.SortFunc on 16-byte records, mostly in reflection-based swaps.
  • Read -gcflags=-m=2, go tool nm and pprof before guessing. go.shape in a symbol name tells you that code is shared, and a method frame above it tells you each element pays for a call.

Every number in this post came from the same loop as the rest of this series: measure, change one thing, measure again, and keep a change only when the counters improve. That loop is how the self-improvement (RSI) loop in Hive, Lamplit Labs’ open-source agent harness for an AI-native SDLC, decides whether an agent’s change to a project is kept. It is a baseline, a variant, a check that measures both, and a rule for accepting the change. The harness, measure and summarise scripts here are built so that a check like this can run again on every change.

This post is licensed under CC BY 4.0 by the author.