Performance of Generics in Go

Monomorphization vs Dictionary Passing

Go implements generics via monomorphization, generating type-specific code at compile time to ensure zero runtime overhead compared to dictionary passing.

Go uses monomorphization, not dictionary passing, to implement generics. The compiler generates a separate copy of generic code for each concrete type used, eliminating runtime type dispatch overhead. This approach ensures that generic functions run at the same speed as non-generic equivalents by resolving all types at compile time.

// The compiler generates distinct functions: SortInt and SortString
func Sort[T comparable](s []T) {
    // Logic compiled once per type T
}

Sort([]int{3, 1, 2})   // Calls SortInt (monomorphized)
Sort([]string{"b", "a"}) // Calls SortString (monomorphized)