https://godbolt.org/z/dvxhnqbeW https://godbolt.org/z/4q8ej77Ke
Shows rust generates 10x more instructions than C++ due to panic messages and optimizations hurting.
https://godbolt.org/z/dvxhnqbeW https://godbolt.org/z/4q8ej77Ke
Shows rust generates 10x more instructions than C++ due to panic messages and optimizations hurting.
Is it possible to make Rust implementation to be on par with C++ in terms of performance for that particular example without using unsafe?
Here's a fair comparison with C++:
https://godbolt.org/z/qh5n49Y69 https://godbolt.org/z/rdET7aT5d
As you can see the Rust version is faster (the only major difference is Rust embeds more information about the panic locations rather than having a single shared message for the exception).
In either case though I wouldn't write the Rust or C++ that way, I'd write a single expression that filled in all the values at once rather than doing them line by line after checking the size a single time. Rust can then elide the bounds check if it knows that you already checked. In Rust and C++ you would should use iterators via for-each loops or a single statement initializer.
(If you want, you can use unsafe and get identical performance to the C++ version using .get_unchecked())
It gives you all bounds checking you need.
In fact, a lot of Linux distributions (like Fedora) built all packages with _GLIBCXX_ASSERTIONS by default.
If you want to have 0 runtime checks, like the C++ example, you can
1) make it unsafe and actively dangerous, like the C++ version
2) change the API so minimum length is guaranteed (probably possible in rust, harder in C++)
3) have the function private/inline where sufficient length is known/can be deduced and the check will be omitted
It gives you all bounds checking you need.
In fact, a lot of Linux distributions (like Fedora) built all packages with _GLIBCXX_ASSERTIONS by default.
Effectively it results in the same assembly as for the completely unsafe C++ code, apart from the 3 instructions which test slice length. During normal operation they are trivial for branch predictor, so their impact will be negligible in the most cases (but not always, e.g. if this function is part of a hot loop, but then inlining should come to the rescue) and in many cases this check will be removed if compiler is able to prove that the condition is always true. So in the worst case scenario you will lose several cycles on the test instructions and the panic code may slightly increase pressure on I-cache, which I think is a good price to pay for the safety.