liveBook · Manning

Zero-cost abstraction

As explained in Code Like a Pro in Rust

A zero-cost abstraction is a high-level programming construct whose compiled implementation has no runtime overhead beyond an equivalent low-level implementation.

A zero-cost abstraction lets you express an operation in high-level Rust without adding runtime overhead beyond the resulting low-level implementation. Rust relies on its compiler and LLVM to turn that code into optimized machine code. Compile in release mode to take advantage of those optimizations. section 11.1 section 11.0 section 11.7

The promise is not that every convenient feature is free. Rust does not build familiar forms of virtual methods, reflection, function overloading, or optional arguments into the language. Where runtime dispatch is needed, choose it explicitly: a value stored as `Box<dyn MyTrait>` uses a vtable lookup for trait-method calls. section 11.1

Watch the dispatch cost

Virtual-method calls require vtable lookups. The cost may be minor for an occasional call but can matter inside a tight loop over many elements. Use a trait object when that dispatch is useful; do not assume it has the same cost as code that avoids runtime dispatch. section 11.1

Start with clear Rust abstractions rather than hand-tuning every operation. When performance needs closer attention, distinguish compiler-optimized code from overhead you explicitly introduced, and assess the release build. section 11.0 section 11.1 section 11.7

How Code Like a Pro in Rust covers it

How deep it goes
Defines the runtime-overhead promise and explains the trait-object exception through vtable dispatch, without showing generated machine code.
Examples
Uses `Box<dyn MyTrait>` and virtual-method calls inside a tight loop to illustrate explicit dispatch overhead.
What it assumes
Assumes familiarity with high-level programming features such as virtual methods and reflection while defining zero-cost abstraction directly.
What you can do after
Evaluate/understand when high-level Rust code can rely on compiler optimization and when chosen runtime dispatch adds a cost.
How it connects
Connects zero-cost abstractions to LLVM optimization, trait objects, dynamic dispatch, reflection, and release builds.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Code Like a Pro in Rust. The section links point to the parts of the book it draws on.