What Is Monomorphization and How Does It Affect Performance?

Monomorphization is the compiler technique that creates specialized code for each generic type usage, ensuring zero-runtime overhead and optimal performance.

Monomorphization is the process where the Rust compiler generates a separate, specialized version of a generic function or struct for each concrete type used in the code, resulting in highly optimized machine code with no runtime overhead. This means that when you use a generic like fn largest<T>(list: &[T]) -> &T, the compiler creates distinct functions such as largest_i32 and largest_char during compilation, allowing the CPU to execute type-specific instructions directly.

fn largest<T: PartialOrd>(list: &[T]) -> &T {
    let mut largest = &list[0];
    for item in list {
        if item > largest {
            largest = item;
        }
    }
    largest
}

fn main() {
    let ints = vec![34, 50, 25];
    let chars = vec!['a', 'z', 'm'];
    // The compiler generates two distinct functions: largest_i32 and largest_char
    let _max_int = largest(&ints);
    let _max_char = largest(&chars);
}