Unsafe code vs. dancing with the optimizer

Note that almost nothing is "guaranteed" when you're talking performance. Even inline(always) is technically just a hint. Even if you manually remove the bounds checks with unsafe code, it's still depending on the optimizer doings a bunch of clever vectorization to make it actually perform well -- but that's an advantage, because it lets the compiler adapt it to the target-cpu in a way that's not feasible (sometimes not even possible) in the library itself.

So while nothing is guaranteed, there's a few patterns that make it easy on the optimizer, and thus reliable in practice.

And to me, the magic of Rust is all about letting you write safe code that optimizes well instead of needing to do the unsafe yourself.

4 Likes