Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Rust implement Zero-cost abstraction for NewTypes Pattern

Tags:

rust

From the unofficial Rust Design Patterns:

Newtypes are a zero-cost abstraction - there is no runtime overhead.

Does LLVM do some magic?

like image 529
wangliqiu2021 Avatar asked Dec 08 '25 06:12

wangliqiu2021


1 Answers

In a language like Python, wrapping a value in a type has overhead, because the wrapper exists as a runtime object, and looking up the wrapped value takes an extra step. In Rust, all types exist only at compile time. A value wrapped is represented exactly the same way as an unwrapped value, and direct access to that value is the same regardless of whether it's in a newtype wrapper or not.

You often want to implement some methods on the newtype wrapper that forward to the wrapped value. LLVM will generally inline these methods, so calling them is the same as calling a method on the underlying value. This is about the only place where (relatively simple) compiler optimizations come into play – no magic needed.

like image 70
Sven Marnach Avatar answered Dec 09 '25 20:12

Sven Marnach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!