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

Consider the for loop with indexes, rewritten a bit to make the operations that happen more clear:

let mut i = 0;
let len = vec.len();

while i < len {
    vec[i] = i;
    
    i += 1;
}

In this example, both i < len and vec[i] contain a runtime-check that i is less than len. In this simple example, the compiler can probably remove the vec[i] bounds check, but it may not be able to in more complicated examples. With iterators, the second bounds check does not even appear in the unoptimized code due to an unsafe block inside the iterator.

4 Likes