Sub topic 10
Taming monomorphization
This chapter assumes you can read Rust generics and trait bounds, and that you have run cargo build --timings from the earlier chapters. Here you will learn why generic code costs compile time, how to find the worst offenders, and which refactors reduce the cost without hurting the design of your code.
What monomorphization does
Rust compiles generic functions by monomorphization. For every distinct set of concrete types a generic function is used with, the compiler produces a separate, specialized copy of the function. A call to max::<i32> and a call to max::<String> produce two different functions in the output.
This is why generic Rust code is fast at runtime. Each copy is optimized for its types, and calls can be inlined. The price is paid at build time:
- rustc must type-check and lower each instance to LLVM IR.
- LLVM must optimize and generate machine code for each instance.
- The linker must handle more symbols and more bytes.
A small generic function used with five types costs five times as much backend work as a plain function. A large generic function that calls other generic functions multiplies this further, because each instance pulls in its own instances of its callees.
Finding the bloat
Do not guess which generics are expensive. cargo llvm-lines counts the lines of LLVM IR generated for each function and how many copies exist.
cargo install cargo-llvm-lines
cargo llvm-lines | head -20The output has three columns: lines of IR, the percentage of the total, and the number of copies, followed by the function name. Read it in two ways:
- A large line count with one copy is just a big function. Monomorphization is not the issue.
- A moderate line count with many copies is the pattern to attack. Total cost is lines multiplied by copies.
Names such as core::option::Option<T>::map, Vec<T>::push or core::ptr::drop_in_place often appear near the top. You cannot remove these, since they come from the standard library. Look further down for functions from your own crates, or from a dependency you control, that have a high copy count.
A related tool is cargo expand, which shows what macros generate. A macro that expands to a generic function or trait impl for many types is a common hidden source of copies.
Technique 1: a thin generic wrapper over a non-generic inner function
Many standard APIs accept impl AsRef<Path>, impl Into<String> or impl AsRef<str> for convenience. The convenience is fine. The problem arises when the whole function body sits behind the generic parameter, so every caller type gets a full copy.
The fix is to convert the argument immediately, then call a non-generic function that does the real work. The standard library uses this pattern itself, for example in std::fs::read_to_string.
use std::io;
use std::path::Path;
// The generic wrapper is tiny, so each instantiation is cheap.
pub fn read_file<P: AsRef<Path>>(path: P) -> io::Result<String> {
read_file_inner(path.as_ref())
}
// The real work is compiled only once.
fn read_file_inner(path: &Path) -> io::Result<String> {
std::fs::read_to_string(path)
}
fn main() -> io::Result<()> {
let text = read_file("Cargo.toml")?;
println!("{} bytes", text.len());
Ok(())
}The public signature is unchanged, so callers notice nothing. Only the wrapper is duplicated for &str, String and PathBuf, and each copy is a few instructions.
The same idea works for methods that take impl Into<String>:
pub struct User {
name: String,
}
impl User {
pub fn set_name(&mut self, name: impl Into<String>) {
self.set_name_inner(name.into());
}
fn set_name_inner(&mut self, name: String) {
// Imagine validation, logging and bookkeeping here.
self.name = name;
}
}
fn main() {
let mut user = User { name: String::new() };
user.set_name("ada");
user.set_name(String::from("grace"));
println!("{}", user.name);
}Use this technique when the function body is large and the number of distinct argument types is more than one or two. For a three-line function it adds noise and saves nothing.
Technique 2: use `dyn Trait` where speed does not matter
A trait object (&dyn Trait or Box<dyn Trait>) uses dynamic dispatch. The compiler generates one copy of the function that works on any implementer through a vtable, which is a table of function pointers. There is no per-type copy.
use std::fmt::Display;
fn show_all_generic<T: Display>(items: &[T]) {
for item in items {
println!("{item}");
}
}
fn show_all_dyn(items: &[&dyn Display]) {
for item in items {
println!("{item}");
}
}
fn main() {
// Two instantiations: T = i32 and T = &str.
show_all_generic(&[1, 2, 3]);
show_all_generic(&["a", "b"]);
// One compiled function handles mixed types.
let mixed: [&dyn Display; 3] = [&1, &"a", &2.5];
show_all_dyn(&mixed);
}Dynamic dispatch has a runtime cost: an indirect call per method call, and no inlining across the call. That cost is irrelevant for code that logs, parses configuration, builds a UI, or handles requests. It matters in tight numeric loops and iterator pipelines.
A rule of thumb: keep generics in hot paths and at the edges of your public API, and use dyn in cold, large, or plugin-like code. Closures stored as Box<dyn Fn(...)> are a typical example. Each closure has a unique type, so a generic function taking F: Fn() is instantiated once per closure passed in.
Technique 3: shrink what is generic
Sometimes only part of a function depends on the type parameter. Pull the type-independent part out into its own function, so the generic part stays small. Typical candidates:
- Error construction and formatting code. Move it into a
#[cold]non-generic function. - Loops over raw bytes or slices after the generic code has converted its input.
- Large
matchblocks that do not mentionT.
Also check the type parameters you have. A struct such as Parser<R: Read, W: Write, L: Logger> forces every method to be instantiated for each combination. If Logger only receives occasional messages, make it Box<dyn Logger> and remove one parameter from the whole type.
Things that make it worse or hide it
#[inline]on large functions.#[inline]makes the function available to every crate that uses it, and the function is then compiled in each of them. Use it for small functions. Do not add#[inline(always)]to build-time-sensitive large functions.- Generics in library crates. A generic function cannot be compiled ahead of time in its home crate, because the types are unknown. Each downstream crate compiles its own copies. A workspace with many crates calling one generic helper with the same types repeats that work. Debug builds already reuse some instances across crates through the
share-genericssetting, but this does not apply to release builds by default. - Derive and macro-heavy code. A derive on a type with many generic parameters generates impls that are instantiated per use. Check
cargo llvm-linesandcargo expandbefore assuming the cause. - Iterator chains. Long
map/filter/collectchains create deeply nested types, and each closure adds a new type. This is fine in small amounts. It becomes expensive when the chain appears in generic code that is itself instantiated many times.
A workflow you can repeat
- Run
cargo llvm-lines | head -30on a clean debug build. - Pick the function from your own code with the highest copy count multiplied by lines.
- Choose the cheapest fix: an inner non-generic function first, then removing a type parameter, then
dyn Trait. - Rebuild with
cargo build --timingsand compare the crate's compile time. - Run your benchmarks or tests if the function is on a hot path.
Expect modest gains. Monomorphization is rarely the largest cost in a build. Dependencies, linking and profile settings often matter more. This is one of the techniques to apply once the earlier measurements point at one crate with heavy generic code.
Summary of trade-offs
| Technique | Compile-time effect | Runtime effect | Best for |
|---|---|---|---|
| Inner non-generic function | Fewer large copies | None | Public APIs with `AsRef` or `Into` arguments |
| `dyn Trait` | One copy for all types | Indirect call, less inlining | Cold paths, plugins, callbacks |
| Remove a type parameter | Fewer combinations | Small, if any | Structs with many parameters |
| Extract type-independent code | Smaller generic bodies | None | Large generic functions with shared logic |
Exercise
cargo llvm-lines shows my_crate::process<T> at 400 lines with 12 copies, and my_crate::big_report at 3000 lines with 1 copy. Which one is the better target for a monomorphization fix, and what is the first change you would try?
Show answer
process<T> is the better target. Its total cost is about 4800 lines of IR (400 x 12), more than big_report, and the cost comes from duplication. big_report has one copy, so making it non-generic would change nothing. For process<T>, first move the type-independent body into a non-generic inner function that takes a concrete type such as &[u8] or &Path, and keep a thin generic wrapper that converts the argument. If the type parameter is needed throughout, consider &dyn Trait when the function is not on a hot path. Then rebuild and compare with cargo build --timings.