Iterators vs Array access (in terms of compiler optimizations?)

Dear Rustaceans,

https://rust-embedded.github.io/book/c-tips/index.html#iterators-vs-array-access

In the above link, it is mentioned that

indexed access can be slower (as it needs to be bounds checked) and may prevent various compiler optimisations.

I did check how two different versions of array accesses(indexing vs iterators) are compiled down to assembly with [https://godbolt.org/](Compiler Explorer). I would love to learn more about how array accesses can actually prevent various compiler optimisations, but currently I can't think of any optimizations that could be prevented by array accesses. Any advice would be greatly appreciated! Thank you :smiley:

Because arrays accesses are bounds checked in Rust, putting a panic edge that interferes with optimization. Iterators don't suffer from this problem.

C and C++ don't have these checks on array accesses. So they don't have this problem.

3 Likes

Thanks for the response! May I ask how an extra panic edge in the control flow graph would interfere with optimization?

Because LLVM would have to prove that the panic will never happen in order to auto-vectorize the loop. Auto-vectorizing loops is a large source of performance gains, so losing it is bad.

5 Likes