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 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.
uint64is 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.
| variant | what it is |
|---|---|
concrete | the hand-written loop over []Rec |
gen-func | MaxFunc[Rec] with func(a, b Rec) bool { return a.Key < b.Key } |
gen-key | MaxKey[Rec, uint64] with a key func and cmp.Ordered keys |
gen-method | MaxBy[Rec], which calls the Less method |
gen-func-noinl | MaxFunc marked //go:noinline, like a generic function that is too big to inline |
gen-lessof | a 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 |
*-ptr | the same over []*Rec, pointing into one contiguous array |
*-u64 | the 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
variant (16-byte Rec values) | cycles / element | instructions / element | vs hand-written |
|---|---|---|---|
| hand-written loop | 2.06 | 8.0 | 1.00x |
MaxFunc[Rec] + func literal | 2.07 | 9.0 | 1.01x |
MaxKey[Rec, uint64] + key func | 2.16 | 9.0 | 1.05x |
MaxBy[Rec], Less method | 7.24 | 33.1 | 3.51x |
MaxFunc, not inlined | 7.24 | 32.1 | 3.51x |
LessOf[Rec], inlined, method | 8.10 | 42.1 | 3.93x |
[]LessI interface values | 9.11 | 36.1 | 4.42x |
Three things stand out:
- 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
MaxFuncinlined. - The same generic loop with a method constraint took 3.5 times the cycles.
MaxBy[Rec]is no longer thanMaxFunc, but it ran 33 instructions per element against 9. - An inlined generic that calls a method is still slow.
LessOfis 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:
The names show the mechanism:
MaxBy[go.shape.struct { Key uint64; ID uint32; Score float32 }]is compiled code for a shape, not forRec. 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.MaxFuncandLessOfdo not appear in the binary as functions.MaxFunccosts 42 andLessOf66, so both inlined intomain.runScanat every call site. ForMaxFuncthe func literal inlined with it. ForLessOf, as the assembly below shows, theLessmethod 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:
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 / element | instructions / element | vs hand-written |
|---|---|---|---|
| hand-written loop | 1.61 | 11.0 | 1.00x |
MaxFunc[*Rec] + func literal | 1.58 | 11.0 | 0.98x |
MaxByP[*Rec], PLess method | 7.78 | 24.1 | 4.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:
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:
| sort call | cycles / element, n=1,000 | n=100,000 | instructions, 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.Sliceis the slow one. It took 1.5-1.7x the cycles ofslices.SortFuncand ran 2.1x the instructions. It does not know the element type, so it swaps through reflection.slices.SortFunctakes a func, not a method. Its comparison is a func value, just likeMaxFunc.sort.Sorttook 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.Sorton[]uint64compares with one instruction and moves 8 bytes instead of 16.
pprof shows where sort.Slice’s extra time goes:
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
funcargument, not as a method in the constraint. That is theslices.SortFunc/slices.MaxFuncdesign. 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.
MaxFunccost 42 against a budget of 80. The sameMaxFuncwith inlining switched off was as slow as the method version (7.24 cycles). Check withgo 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.Slicewithslices.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 -lon macOS andperf stat -e cycles,instructionson 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-lineLessOf3.9x. Each one had an indirectCALLthrough the dictionary for every element. - A generic func argument that inlines costs nothing.
MaxFunc[Rec]cost 1.01x andMaxFunc[*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
MaxFuncwithout inlining cost 3.5x. sort.Slicecosts 1.5-1.7x the cycles ofslices.SortFuncon 16-byte records, mostly in reflection-based swaps.- Read
-gcflags=-m=2,go tool nmand pprof before guessing.go.shapein 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.
Related posts
- Go PGO in Practice: What go build -pgo Changed in a Log Router, Measured: another post where inlining is the whole story, and where PGO’s devirtualization did nothing.
- False Sharing in Go on Apple Silicon: Cache-Line Padding, Measured: the same measurement method on the same machine, with cycles and instructions per operation.
- Go pprof profiling guide: CPU, goroutine and mutex profiles: how to collect and read the CPU profiles shown above.
- Rust vs Go for a CLI Tool: why Go builds fast and does not monomorphise generics for every call site, and what that means in practice.
- Hive: Lamplit Labs’ open-source, self-improving (RSI) agent harness: the product mentioned above.

![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.](/assets/img/posts/performance/go-generics-scan-cycles.webp)



![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).](/assets/img/posts/performance/go-generics-sort-cycles.webp)
