What are zero-cost abstractions and monomorphization in Rust?
Answer
Zero-cost abstractions is Rust's guarantee that high-level constructs (iterators, generics, trait implementations, async/await) compile down to code as efficient as hand-written low-level code — you don't pay a runtime cost for the abstraction layer. The mechanism behind this for generics is monomorphization: when the compiler encounters a generic function like fn max<T: Ord>(a: T, b: T) -> T, it generates a separate, fully concrete copy of the function for each unique type it is called with (max_i32, max_f64, etc.) at compile time. Each monomorphized copy can be fully optimized and inlined by LLVM. The trade-off is longer compile times and larger binary sizes compared to dynamic dispatch, but zero runtime overhead. Iterator chains are a canonical example: they compile to tight loops with no heap allocation or function call overhead.
Previous
What is a HashMap in Rust and how is it used?
Next
What are Pin<T> and Unpin in Rust async programming?
More Rust Questions
View all →- Advanced What are Pin<T> and Unpin in Rust async programming?
- Advanced How does the async runtime work internally in Rust (Waker, Poll, Executor)?
- Advanced What are the rules for writing correct unsafe Rust?
- Advanced How does Rust FFI (Foreign Function Interface) work with C?
- Advanced What is procedural macro metaprogramming with syn, quote, and proc_macro2?