Sub topic 10
Taming monomorphization
This chapter assumes you can write generic Rust functions with trait bounds, and that you have run cargo build --timings from the earlier measuring chapter.
What monomorphization costs
Rust compiles generic code by monomorphization. For every concrete type a generic function is used with, the compiler generates a separate copy of that function. A function called with String, &str and PathBuf becomes three functions in LLVM IR, and LLVM optimizes and emits machine code for each one.
Copies are fast at runtime, but they add work to rustc, LLVM and the linker. They also make binaries larger. The cost is highest when a large generic function is used with many types, or when a generic function sits in a widely used library.
Find the bloat first
Do not rewrite generics on a hunch. cargo llvm-lines counts the lines of LLVM IR per function and shows how many copies exist.
cargo install cargo-llvm-lines
cargo llvm-lines | head -20The output lists each function with its total lines and its copy count. Look for entries with a large line count and many copies. Those are the candidates. A small function with many copies costs little, and a large function with one copy is not a monomorphization problem.
Move the body into a non-generic inner function
A common fix is to keep the generic function as a thin wrapper. It converts its argument to a concrete type and calls a non-generic function that holds the real work.
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 a = read_file("Cargo.toml")?;
let b = read_file(String::from("Cargo.toml"))?;
println!("{} {}", a.len(), b.len());
Ok(())
}Each call with a different P still creates a copy of read_file, but that copy is one call and a conversion. The file-reading logic exists once. The standard library uses this pattern for functions like std::fs::read_to_string.
Use dynamic dispatch where speed does not matter
A &dyn Trait or Box<dyn Trait> parameter compiles the function once and calls methods through a vtable. This avoids copies entirely. The trade-off is a small runtime cost per call, and the compiler can no longer inline through the call.
use std::fmt::Display;
fn log_generic<T: Display>(value: T) {
println!("[log] {value}");
}
fn log_dyn(value: &dyn Display) {
println!("[log] {value}");
}
fn main() {
log_generic(1);
log_generic("two");
log_dyn(&3.0);
log_dyn(&"four");
}log_generic is compiled for i32 and &str. log_dyn is compiled once. Use dyn for code that is not on a hot path, such as logging, error reporting and setup.
Other sources of duplicate code
- Closures. Every closure has its own unique type. A generic function that takes a closure is compiled once per call site. Accept
&dyn Fn(...)for large functions that are called from many places. - Iterator chains. Long adapter chains create deeply nested types. Collecting into a
Vecat a module boundary keeps the types short. - Generic code in a library. Downstream crates instantiate it, so the cost shows up in their build and not in the library's.
Check the result
Run cargo llvm-lines again after a change and compare the line count and copy count for the function you edited. Then compare cargo build --timings before and after. If the total time barely moves, the function was not a real bottleneck, and you can revert the change to keep the code simpler.
Exercise
A function fn parse<S: AsRef<str>>(s: S) -> Config has 400 lines of logic and is called with String, &str and Cow<str>. Describe how to reduce its compile cost, and explain why the change helps.
Show answer
Make parse a thin wrapper that calls fn parse_inner(s: &str) -> Config with s.as_ref(). Move all 400 lines into parse_inner. The wrapper is still compiled three times, but it is tiny. The 400 lines are compiled and optimized once, which lowers the LLVM IR size and the work for LLVM and the linker.
Exercise
Which tool shows how many copies of each generic function exist, and what two numbers do you look for in its output?
Show answer
cargo llvm-lines shows this. Look for functions with a large total line count and a high copy count. A function that is large but has one copy, or has many copies but is tiny, is not worth changing.