3 ms·
Iterating over an array in Rust does not involve bounds checking every access since Rust guarantees immutability to the container over the course of the iterati
by Maxatar 2y ago
Iterating over an array in Rust does not involve bounds checking every access since Rust guarantees immutability to the container over the course of the iteration. Hence all that's needed is to access the size of the array at the start of the iteration and then it is safe to iterate over the entire array.
Note that this is not something C++ is able to do, and C++ has notoriously subtle iterator invalidation rules as a consequence.
- CyberDildonics 2y agoThey asked for evidence of bounds checks being expensive, please try to keep the context in mind. Note that this is not something C++ is able to do Or you could just not mutate the container.
- Maxatar 2y agoIt's the optimization that C++ is unable to perform, not the immutability.
- pptr 2y agoIf you declare using an invalidated iterator as UB, the compiler can optimize as if the container was effectively immutable during the loop.
- CyberDildonics 2y agoAre you talking about optimizing out bounds checking that isn't happening in the first place?
- jodrellblank 2y ago> "They asked for evidence of bounds checks being expensive" They said "bounds-checking penalties are small" not that it was free. You've described a situation where bounds checking happens and declared that it "should be" expensive because it happens. You haven't given evidence that it's expensive.
- CyberDildonics 2y agoI didn't give direct evidence, that's true. You can profile it yourself, but it is the difference between direct access to cached memory (from prefetching) and two comparisons plus two branches then the memory access. To someone who doesn't care about performance having something trivial become multiple times the cost might be acceptable (people use scripting languages for a reason), but if your time is spent looping through large amounts of data, that extra cost is a problem.