Programming Languages - Zero Cost Abstractions

Updated: 2021-11-19

By Bjarne Stroustrup:

What you don’t use, you don’t pay for. And further: What you do use, you couldn’t hand code any better.

It means paying no penalty for the abstraction: whether you use the abstraction or instead go for the "manual" implementation you end up having the same costs (it doesn’t matter if you use loops or closures, they all compile down to the same assembly).

  • No global costs: A zero cost abstraction ought not to negatively impact the performance of programs that don’t use it. For example, it can’t require every program carry a heavy language runtime to benefit the only programs that use the feature.
  • Optimal performance: A zero cost abstractoin ought to compile to the best implementation of the solution that someone would have written with the lower level primitives. It can’t introduce additional costs that could be avoided without the abstraction.

Generally used with C++, and Rust. Rust makes heavy use of them.

Example

In Python (without zero-cost abstraction)

sum(range(1000))

This does 1,000 iterations and additions every time the code runs.

In Rust (with zero-cost abstraction)

(0..1000).sum()

This compiles down to the constant 499500.