3 ms·
The C++ example is incredibly unsafe as it's not doing any bounds checking so the comparison isn't even fair. You wouldn't write code that way in C++ unless you
by mlindner 5y ago
The C++ example is incredibly unsafe as it's not doing any bounds checking so the comparison isn't even fair. You wouldn't write code that way in C++ unless you have some kind of absolute trust in the caller and the slice was of known fixed size and it was impossible that refactoring would never change the size.
Here's a fair comparison with C++:
https://godbolt.org/z/qh5n49Y69 https://godbolt.org/z/qh5n49Y69 https://godbolt.org/z/rdET7aT5d 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())
- matesz 5y agoThat is amazing, thanks!
- mlindner 5y agoHere's the identical result to the C++ output, for reference. https://godbolt.org/z/6sa3zf555 https://godbolt.org/z/6sa3zf555
- expnkx 5y agoIf you want safety. you can just use _GLIBCXX_ASSERTIONS https://godbolt.org/z/eThdeW3Mv https://godbolt.org/z/eThdeW3Mv 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.