Monomorphization
Subject: Computer and Technology noun /ˌmɑː.noʊ.mɔːr.fəˈzeɪ.ʃən/ 1 definition
- compiler-design
- programming-languages
- type-systems
- computer-science
-
Definition (noun)
Entry #277 · UpdatedMonomorphization is a compile-time transformation in which a compiler eliminates parametric polymorphism by generating a separate, concrete implementation of a generic function, method, or data type for every distinct set of type arguments used in a program. Once type checking and inference resolve each call site and data layout, the compiler substitutes concrete types into the polymorphic definition, computes exact field sizes and alignments, and allows subsequent optimization passes—such as inlining, dead-code elimination, and SIMD vectorization—to specialize each copy independently. Unlike type erasure or dynamic dispatch, which share a single compiled routine across types via boxed pointers or virtual method tables (vtables), monomorphization avoids runtime indirection and unboxing overhead while preserving static dispatch. Its core trade-off is increased compilation time and binary size (known as code bloat) when many instantiations are generated, and its boundary lies at static decidability: constructs with unbounded polymorphic recursion or types resolved only at runtime cannot be monomorphized without dynamic dispatch.
Common Forms
Demand-Driven Instantiation: Generates concrete copies lazily only for type combinations actually invoked or reachable in the program (used in Rust and C++ templates), ensuring unused generic paths emit zero machine code while relying on linker deduplication across compilation units.
Whole-Program Monomorphization: Resolves and specializes every polymorphic function and data structure across the entire program graph in a single compilation pass (as in MLton for Standard ML), enabling aggressive cross-module optimization while precluding incremental per-file linking.
Selective Specialization: Combines default boxed or dictionary-based polymorphism with targeted monomorphization of hot paths and primitive numeric types (used in GHC Haskell and Swift), capturing key performance gains without unbounded executable growth.
Shape-Based Stenciling: Groups concrete types that share an identical memory layout and garbage-collection shape into a single monomorphized stencil parameterized by a compact type dictionary (as implemented in Go generics), trading slight indirection for significantly reduced code duplication.
Example
A Rust telemetry service invokes a single generic helper
fn clamp<T: PartialOrd>(val: T, low: T, high: T) -> Ton bothu32packet counts andf64latency measurements. During compilation,rustcmonomorphizes the function into separateclamp::<u32>andclamp::<f64>instances in LLVM intermediate representation, enabling the backend to emit specialized integercmpand IEEE-754 floating-pointucomisdmachine instructions with zero runtime dispatch overhead.