Sub topic 7
How the compiler compiles generics
This chapter assumes you can write generic functions and structs, add trait bounds, and know the difference between T and &T. It explains what the compiler produces from that code, and why it is fast but can make binaries larger.
One generic function, many machine functions
The CPU has no notion of "any type". Every machine instruction works on a specific size and layout of data. Adding two i32 values and adding two f64 values use different instructions. So the compiler must turn a generic function into concrete code somewhere.
Rust does this with monomorphization. The compiler finds every concrete type that a generic item is used with, then generates a separate copy of the item for each one. The name means "making single-form".
Take the largest function from earlier chapters. After you call it with &[i32] and &[f64], the compiler behaves as if you had written this by hand:
fn largest_i32(items: &[i32]) -> &i32 {
let mut largest = &items[0];
for item in items {
if item > largest {
largest = item;
}
}
largest
}
fn largest_f64(items: &[f64]) -> &f64 {
let mut largest = &items[0];
for item in items {
if item > largest {
largest = item;
}
}
largest
}
fn main() {
println!("{}", largest_i32(&[3, 9, 2]));
println!("{}", largest_f64(&[1.5, 0.2]));
}In the i32 copy, item > largest becomes a plain integer comparison. In the f64 copy it becomes a floating-point comparison. No type check, lookup, or branch happens at run time to decide which comparison to use. That is what "zero-cost abstraction" means here: you pay nothing at run time for having written the code generically.
Seeing the copies
You can observe that each instantiation is a different function with its own type. std::any::type_name and std::mem::size_of are both resolved separately for each copy:
use std::mem::size_of;
fn describe<T>(_value: &T) -> String {
format!("{} takes {} bytes", std::any::type_name::<T>(), size_of::<T>())
}
fn main() {
println!("{}", describe(&1u8));
println!("{}", describe(&1u64));
println!("{}", describe(&"hi"));
}On a 64-bit machine this prints:
u8 takes 1 bytes
u64 takes 8 bytes
&str takes 16 bytesThree calls with three types produce three functions, describe::<u8>, describe::<u64> and describe::<&str>. A &str is 16 bytes because it holds a pointer and a length.
The pipeline
Three details in this pipeline matter in practice.
- Type checking happens before instantiation. The compiler checks the generic body once, using only what the bounds promise. If
Thas noDisplaybound, callingprintln!("{}", x)on aTis an error at the definition, even if you only ever call the function withi32. C++ templates behave differently: they are checked at each use. Rust errors therefore point at the generic code, not at a distant call site. - Only used instantiations exist. A generic function nobody calls produces no machine code. A library can offer thousands of generic functions without adding bytes to your program for the ones you skip.
- Each copy is optimized separately. Because the compiler knows the concrete type, it can inline calls, unroll loops, and use vector instructions in each copy. This is why
iter().map(...).sum()can compile to a tight loop.
What it costs
Monomorphization trades size and build time for run-time speed.
- Binary size. Each distinct type adds a copy of every generic function it reaches. This is called code bloat. A
Vec<T>used with 40 element types brings 40 copies of theVecmethods you call. - Compile time. The compiler does more work, and LLVM must optimize every copy. Heavy generic code is a common reason for slow builds.
- Instruction cache pressure. Many similar copies can compete for the CPU's instruction cache. This is rarely measurable, but it is the reason generics are not always faster in real programs.
Some things do not multiply copies:
- Lifetimes are erased.
longest<'a, T>is copied once perT, not once per lifetime, because lifetimes exist only during checking. - Identical uses share one copy. Calling
largest::<i32>from ten places gives one function, not ten. - Each closure has its own type. Passing two different closures to
mapinstantiatesmaptwice, once per closure. This is usually fine, but it is part of why iterator chains grow the binary. - Const generics multiply too.
sum::<3>andsum::<5>are separate functions, becauseNis part of the type.
Reducing bloat: the inner function pattern
A common source of waste is a generic function whose body does not depend on the type. The usual fix is to convert the argument at the boundary and move the real work into a non-generic inner function:
use std::fs;
use std::io;
use std::path::Path;
fn read_len<P: AsRef<Path>>(path: P) -> io::Result<usize> {
fn inner(path: &Path) -> io::Result<usize> {
Ok(fs::read(path)?.len())
}
inner(path.as_ref())
}
fn main() {
println!("{}", read_len("/no/such/file").is_err());
}The generic wrapper is tiny, so each P costs only a few instructions. The file-reading code exists once. The standard library uses this pattern for functions such as std::fs::read, which accept impl AsRef<Path>.
Static and dynamic dispatch side by side
Monomorphization is called static dispatch: the call target is fixed at compile time. A trait object (dyn Trait) uses dynamic dispatch: one copy of the code calls through a table of function pointers, a vtable, at run time.
trait Shape {
fn area(&self) -> f64;
}
struct Square(f64);
struct Circle(f64);
impl Shape for Square {
fn area(&self) -> f64 {
self.0 * self.0
}
}
impl Shape for Circle {
fn area(&self) -> f64 {
3.0 * self.0 * self.0
}
}
fn total_static<S: Shape>(shapes: &[S]) -> f64 {
shapes.iter().map(|s| s.area()).sum()
}
fn total_dyn(shapes: &[Box<dyn Shape>]) -> f64 {
shapes.iter().map(|s| s.area()).sum()
}
fn main() {
println!("{}", total_static(&[Square(2.0), Square(3.0)]));
println!("{}", total_static(&[Circle(1.0)]));
let mixed: Vec<Box<dyn Shape>> = vec![Box::new(Square(2.0)), Box::new(Circle(1.0))];
println!("{}", total_dyn(&mixed));
}This prints 13, 3 and 7. total_static is compiled twice, once for Square and once for Circle, and each copy can inline area. total_dyn is compiled once, and each call to area goes through the vtable. It is the only version that can hold a Square and a Circle in the same slice.
| Property | Generics (`T: Trait`) | Trait objects (`dyn Trait`) |
|---|---|---|
| Dispatch | Static, resolved at compile time | Dynamic, through a vtable |
| Code size | One copy per type | One copy total |
| Inlining across the call | Possible | Usually not possible |
| Mixed types in one collection | No, one `T` per collection | Yes |
| Concrete type known at compile time | Yes | No |
Practical gotchas
- Unbounded recursion. A generic function that calls itself with a growing type, such as
f::<Vec<T>>insidef::<T>, creates infinitely many instantiations. The compiler stops with a "reached the recursion limit while instantiating" error. - Library generics are compiled in your crate. A generic function in a dependency has no machine code until you instantiate it, so its internal representation ships with the library and your build does the work. Non-generic functions are compiled once, inside the library.
- Do not assume bigger means slower. Measure first. Switch to
dyn Traitwhen build time or binary size is a real problem, or when you need a mixed collection. Do not switch based on guesses.
Exercise
A function fn parse_all<S: AsRef<str>>(items: &[S]) -> Vec<i32> is called with &[&str], &[String] and &[Box<str>] in one program. How many machine-code versions of it does the compiler generate, and how could you reduce that number without changing the public signature?
Show answer
Three, one for each distinct S. To reduce it, keep the signature but move the body into a non-generic inner function that takes &[&str], or convert each item with as_ref() into a Vec<&str> and pass that to the inner function. The generic outer function then becomes a thin wrapper, and the parsing code exists once.
Exercise
A teammate says that Vec<Box<dyn Shape>> is always slower than a generic Vec<S> where S: Shape. Give one reason this is often true and one reason the claim is too strong.
Show answer
Often true: calls through a vtable cannot be inlined, so the compiler cannot optimize across them, and each call needs an indirect jump. Too strong: the extra cost per call is small, a program is often limited by other work, and the generic version cannot hold mixed types at all. The generic version also adds binary size and build time, which can matter more than a per-call cost.