Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Rust performs a runtime check to protect against out of bounds array accesses. In some cases those checks can be optimized out if the compiler can prove it's not needed.


This is my point precisely. Having proven to itself that 0 <= x < 8, the compiler could go on to remove any test for x < 8, right?


Yes, and the compiler does that. That's one of the reasons that iterators are preferred over for-loops with manual access in Rust. While compilers can for very simple cases determine that you will always stay within the bounds (as in your example, where it can find at compile time that the length will always be 8 and no access outside happens) with iterators the compiler doesn't need to know the actual length and can always elide bound checks.


The Rust compiler is smarter than that. Even for classic subscript-type loops, it can often elide the bounds checks. There was a discussion on this in HN a few months back, with machine code excerpts. An iterator and an explicit loop with subscripts both generated the same machine instructions.

If the compiler can elide bounds checks in inner loops, that's usually enough. Bounds checks elsewhere rarely affect performance.


Pedantic note: compiler doesn’t elide bounds checks in code using iterators. They’re not there to begin with. Iterators in the standard library are implemented using unsafe code, which calls non-bounds-checking variants of functions getting elements from collections. There is nothing for the compiler left to do here regarding bounds-checking.


Pedantic, but interesting - didn't know that. Thanks!


Yes. It even does so in some cases.




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

Search: