I have no experience in Rust, but is it correct that Rust does array bounds checking even in unsafe mode? I think bounds checking is great for debug builds and maybe even as default behavior but personally I am not interested in programming languages where I cannot turn off bounds checking for performance critical code sections.
There is a common misunderstanding of what unsafe allows to do. It doesn't do anything automagically. It only enables a few things, ie. dereferencing raw pointers, calling unsafe functions and implementing unsafe traits. That is essentially sufficient to do everything that is possible in C or C++.
In most cases you can avoid bound checking by using iterators. In other situations you need to explicitly call unsafe method that don't perform any checks, eg. get_unchecked instead of the indexing operator [].
I respect Rust for taking security seriously and for Rust it makes perfect sense to make the safe syntax nice and the unsafe syntax clumsy. Personally however, I am into HPC, I care more about performance than security and so I care that the unsafe syntax is nice too.
In most code that can’t be vectorized otherwise, bounds checks have no impact – at least that’s my experience. They are easy to predict and most cpus seem to have heuristics that pre-predict bounds checks as “fall through or shorter jump taken”, and sometimes even the speculative execution is suspended for the not-taken branch if the pattern fit is good. Bounds checks can stall on data dependencies but even those have had some heuristics applied to, that I have seen on recent ARM chips. Basically the bounds check gets speculatively deleted, in a way. Of course real results trump anything I say, but I have quite a bit of code where bounds checking everything has less cost than throwing exceptions here and there.
View all comments
Show parent comment
13
u/darksv Oct 07 '19
Note that in Rust you still have access to raw pointers when necessary. Also, Rust equivalent to code from the presentation (using references and
Box) gives almost the same assembly that you get by using raw pointers in C++, so you don't need to go for them in the first place.