We all know `iter` is faster than `loop`, but why?

This is a nuanced test for silly reasons. The functions are taking &mut Vec<usize> but not changing the length of the Vec. If you change them to take &mut [usize] instead -- nothing else needs to change, as the caller continues to work -- then they end up all being equally fast (within error): Rust Playground

So the difference is that the compiler can't currently elide the bounds checks in the exact case, though it can in very similar ones.

Those bounds checks tend not to matter in code with a less-tiny body, because the branch predictor predicts them correctly anyway, but here the body is so small that micro-differences matter.

5 Likes