Why is the performance of `while` said to be slower than `for` when iterating over an array?

Viewed 428

The second edition of The Rust Programming Language states the following about while loops for iterating over an array:

fn main() {
    let a = [10, 20, 30, 40, 50];
    let mut index = 0;

    while index < 5 {
        println!("the value is: {}", a[index]);

        index = index + 1;
    }
}

[...] It’s also slow, because the compiler adds runtime code to perform the conditional check on every element on every iteration through the loop.

As a more efficient alternative, you can use a for loop and execute some code for each item in a collection.

fn main() {
    let a = [10, 20, 30, 40, 50];

    for element in a.iter() {
        println!("the value is: {}", element);
    }
}

In C++ I would expect a compiler/optimizer to produce something with equivalent run-time performance.

Why is this not the case in Rust?

1 Answers
Related