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 write high-level Rust that compiles to optimized machine code without runtime overhead beyond an equivalent low-level implementation. Rust delegates much of its machine-code optimization to LLVM. section 11.1 section 11.0

Zero-cost does not mean every feature is free. Rust lets you introduce runtime overhead explicitly, such as dynamic dispatch through a trait object. That choice makes the cost easier to reason about. section 11.1

Trait objects and dispatch cost

A value stored as `Box<dyn MyTrait>` can call `MyTrait` methods through a vtable lookup. Similar virtual-method lookup costs can become significant in a tight loop over many elements. section 11.1

Compile in release mode to take advantage of optimizations. When performance needs closer attention, investigate the specific costs rather than assuming that every abstraction or dispatch choice is free. section 11.7 section 11.0

How Code Like a Pro in Rust covers it

How deep it goes
Defines the runtime-overhead goal and explains the trade-off between zero-cost abstractions and explicit dynamic dispatch.
Examples
Illustrates vtable dispatch with `Box<dyn MyTrait>` and virtual-method calls in a tight loop.
What you can do after
Evaluate high-level Rust abstractions and recognize when dynamic dispatch introduces runtime overhead.
How it connects
Connects zero-cost abstraction to LLVM optimization, trait objects, dynamic dispatch, and vtables.

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.