2 ms·
The difference is very it depends. In Rust, if you use iterators or make loops simple enough for LLVM to understand, then redundant bounds checks are optimized
by pornel 5y ago
The difference is very it depends.
In Rust, if you use iterators or make loops simple enough for LLVM to understand, then redundant bounds checks are optimized out, so the safety is essentially free.
However, there are certain types of hot loops, like matrix operations, that are too cumbersome to write as 1d iterators, and are too complex for LLVM to prove safe. In that case bounds checks hurt performance a lot. Not because of checks themselves, but because added control flow prevents autovectorization and other optimizations that depend on reordering code.
We need smarter optimizers that understand they can collapse and move bounds checks. Currently `a[1], a[2]` has 2 bounds checks, but `a[2], a[1]` has 1, because the optimizer thinks you care exactly which one of them will fire, rather than merely ensuring the safety.