skip to content

After a Rust generic `mean<T>` is called with many element types, build time and binary size grow; what does monomorphization do, and how do you contain it?

level: seniorimportance: should knowfreq 50%

answer

  1. one copy per type argument set
  2. the helpers it calls multiply too
  3. free at run time, paid at build
  4. a thin generic shell, one inner body

basics

~20 s

rustc compiles a separate copy of a generic function, and of every generic helper it calls, for each distinct set of concrete type arguments. Calls stay direct and inlinable, but copies multiply; keep generic shells thin and delegate to a non-generic inner function.

solid answer

~40 s

Monomorphization means rustc generates code per instantiation: `mean::<u8>`, `mean::<i32>` and `mean::<f32>` become three separate functions, while a second call with `u8` reuses the first copy. Each copy also instantiates the generic code it calls, such as the iterator `map`, `sum` and the closure, so an unoptimised LLVM IR dump of a three-type `mean` defines 27 functions tied to it, nine per type. That is why generic calls cost nothing extra at run time, being direct calls the optimiser can inline, yet cost compile time and binary size, paid by the crate that instantiates them. To contain it, make the generic part a thin conversion shell around a non-generic body, as `std::fs::read<P: AsRef<Path>>` does with its inner `fn inner(path: &Path)`; keep generic signatures narrow; reserve type erasure for cold paths; and count instantiations before refactoring.

code

rust · 20 lines
rust
use std::any::type_name;

fn mean<T: Copy + Into<f64>>(readings: &[T]) -> f64 {
    let sum: f64 = readings.iter().map(|&r| r.into()).sum();
    sum / readings.len() as f64
}

fn label<T>(_: &[T]) -> &'static str {
    type_name::<T>()
}

fn main() {
    let a = [1u8, 2, 3];
    let b = [10i32, 20];
    let c = [0.5f32, 1.5];
    println!("{} {}", label(&a), mean(&a));
    println!("{} {}", label(&b), mean(&b));
    println!("{} {}", label(&c), mean(&c));
    println!("{}", mean(&[4u8, 6])); // reuses mean::<u8>
}

go deeper

for a junior

Recall that rustc compiles one copy of a generic function per concrete type it is used with, which is why generic calls are as fast as hand-written ones.

for a middle

Explain that copies are per distinct type-argument set, that each copy instantiates the generic helpers it calls, and where the compile-time bill lands.

for a senior

Diagnose build and size growth by counting instantiations, then apply the inner-function pattern, narrower signatures or type erasure on cold paths.

for a principal

Weigh run-time speed against build time and binary size per crate, and make thin generic shells over concrete cores a review habit for widely used library functions.

## What monomorphization produces **Monomorphization** is how rustc turns generic code into machine code. The Rust Book describes it as filling in the concrete types used when compiled: the compiler looks at every place generic code is called and generates code for each concrete type it is called with. For `fn mean<T: Copy + Into<f64>>(readings: &[T]) -> f64`: - `mean(&[1u8, 2, 3])` produces a function specialised for `u8`; - `mean(&[10i32, 20])` produces a second one for `i32`; - `mean(&[0.5f32, 1.5])` produces a third for `f32`; - a later `mean(&[4u8, 6])` produces nothing new, because a copy for `u8` already exists in this crate. The unit is the **distinct set of type arguments**, not the call site. A generic struct works the same way: `Cache<String, f64>` and `Cache<u32, Vec<u8>>` each get their own compiled methods. ## The copies multiply downward A generic function rarely stands alone. `mean`'s body calls `iter`, `map`, `sum` and a closure, and each of those is generic over the types that flow into it. Instantiating `mean::<u8>` therefore instantiates `Map<Iter<u8>, closure>`, its `fold`, `Sum::sum` for that iterator and the closure body. Compiling the three-type program below with `--emit=llvm-ir -C opt-level=0` shows exactly three definitions of `mean` itself, one per type, and 27 function definitions whose symbols mention it, nine per type. The release optimiser inlines many of these away, but each must still be generated and optimised, which is where compile time goes. ## The trade-off | Aspect | Monomorphized generic call | |---|---| | Dispatch | a direct call to the copy for that type | | Inlining | the optimiser sees concrete types and can inline and specialise | | Run-time cost | none beyond a hand-written function for that type | | Compile time | grows with each distinct instantiation and its helpers | | Binary size | each instantiation adds code unless the optimiser inlines or removes it | | Where the cost lands | in the crate that supplies the concrete types, usually the caller | The alternative strategy, compiling one body that reaches its type's operations through a table of function pointers, is what a trait object provides; that side is covered with dynamic dispatch, and the general comparison with generic programming theory. ## Containing the growth 1. **Thin generic shell, non-generic core.** Do the type-dependent work in a few lines, then hand a concrete type to an inner function that is compiled once. 2. **Narrow the generic surface.** Take `&[T]` or `&str` instead of `impl IntoIterator` or `impl AsRef<str>` where callers can convert cheaply, so fewer distinct types reach the function. 3. **Convert early.** If every path ends in `f64`, a public function taking `&[f64]` beside a small generic convenience wrapper keeps the heavy code single. 4. **Erase types on cold paths.** Configuration loading or error reporting rarely needs inlining, so a `&dyn Trait` parameter there trades a negligible indirect call for one compiled copy. 5. **Measure before refactoring.** Count instantiations in `--emit=llvm-ir` output or in a symbol-size report from the release binary, and fix the few functions that dominate. ## The inner-function pattern in std `std::fs::read` is declared `pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>>`. Its body defines `fn inner(path: &Path) -> io::Result<Vec<u8>>`, which opens the file and reads it, and ends with `inner(path.as_ref())`. Callers pass `&str`, `String`, `&Path` or `PathBuf`, and each gets a tiny outer copy that only calls `as_ref`, while the file-reading body exists once. `fs::read_to_string` and `fs::write` follow the same pattern. The second example below shows it on a word counter: three outer copies, one `inner`. ## What does not help - `#[inline]` does not reduce the number of instantiations; it is a hint about placing code in callers, and the Reference warns that poor inlining decisions can slow programs down. - Removing bounds does not reduce copies; copies come from distinct type arguments, not from how many traits a parameter needs. - Replacing every generic with `dyn Trait` removes copies but gives up inlining everywhere, including the hot paths that motivated generics.

  • Does calling `mean(&[4u8, 6])` a second time in the same crate create another copy?
    No. Instantiation is per distinct set of type arguments, so both `u8` calls use one `mean::<u8>`; the IR for the example shows three copies for three element types, not four for four calls. A different crate that also calls `mean::<u8>` may generate its own copy.
  • Why is `std::fs::read` written with an inner function?
    The public `read<P: AsRef<Path>>` is instantiated for every path type callers use, such as `&str`, `String` and `PathBuf`. Each instantiation only calls `path.as_ref()` and forwards to the non-generic `inner(path: &Path)`, so the file-opening and reading code is compiled once however many path types appear.
  • Would replacing every `T: Trait` parameter with `&dyn Trait` be the right fix for a slow build?
    Rarely as a blanket rule. It removes the copies, but every call becomes indirect and the optimiser loses the concrete type it needs for inlining, and the trait must be usable as a trait object. Apply it to cold paths after measuring which instantiations dominate, and keep generics where calls are hot.

  • Generic calls in Rust are dispatched through a vtable at run time.
  • rustc compiles a generic function once and shares that code across all types.
  • Marking a generic function #[inline] reduces how many copies get compiled.
  • Monomorphization duplicates only the function you wrote, not the generic helpers it calls.
  • Each call site gets its own copy, even when the type is the same.