From the unofficial Rust Design Patterns:
Newtypes are a zero-cost abstraction - there is no runtime overhead.
Does LLVM do some magic?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With