How Go Generics Balance Performance with GC Shape Stenciling

GC shape stenciling in Go generics

How Go Generics Balance Performance with GC Shape Stenciling

I explored how Go implements generics using GC shape stenciling, a unique middle ground between Rust's full monomorphization and Java's type erasure. By grouping types based on their garbage collector shape, Go reduces binary size while maintaining high performance. This approach compiles shared function bodies for similar types, using hidden dictionaries to handle specific type details at runtime, effectively balancing compile time and execution speed.

The main exception is method calls, which can't be fully resolved at compile time. They can also block inlining and make escape analysis more conservative, which can mean extra heap allocations.
  1. munificent

    Good article. Some related bits that other languages do:

    Swift is able to avoid monomorphizing even when the type arguments have different GC shapes and allocation strategies. To do that, the dictionary (what Swift calls a "witness table") has entries for the functions the memory manager needs to allocate and trace a value of type argument's type.

    Go's notion of dictionary and Swift's witness tables share a lot of DNA with how Haskell compiles generic code using type classes.

    C#/.NET does an interesting hybrid approach. When source code is compiled to .NET bytecode, the generic code is only compiled once. Then at load time, the JIT will take that bytecode and monomorphize it to native code for each instantiation using a value type (primitive or struct). But instantiations of reference types all share a single JITTed implementation.

  2. jchw

    Go's approach to generics is decent. It gets some of the benefits with some of the downsides. When coding in Rust, I am always so desperate for better compile times, especially for "clean" compilation because I make heavy use of Nix for various things and that comes into play a lot. (I don't run all of my builds in Nix, but I use Nix for virtual machine based integration testing for example, and that would involve doing a clean Nix build of the program.) So I guess while I get why some people were disappointed when Go didn't choose full monomorphization I appreciate their commitment to keeping fast compile times a priority. And it is certainly a hell of a lot nicer to be able to do proper generics at the language level on maps and slices in any case.

  3. jaeyoungkim

    A related self-plug, but if anyone wants to see additional examples, I've written a detailed exploration of Go generics as part of a larger Go reverse engineering reference here:

    https://docs.google.com/document/d/1AG76FBur7aagm36o-hNbny1X...

More from this day

2026-07-16