Hacker News new | past | comments | ask | show | jobs | submit login

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.




They 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.


> "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.


I 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.


It's the optimization that C++ is unable to perform, not the immutability.


Are you talking about optimizing out bounds checking that isn't happening in the first place?


If you declare using an invalidated iterator as UB, the compiler can optimize as if the container was effectively immutable during the loop.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: