Why is `while` performance considered slower than` for` when repeating an array?

The second edition of the rust programming language describes the following about 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 is also slow because the compiler adds runtime code to conditionally check each element at each iteration through a loop.

As a more efficient alternative, you can use a for loop and execute code for each item in the 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 the compiler / optimizer to create something with equivalent runtime performance.

Why is this not so in Rust?

+4
source share
1 answer

In C ++, I would expect the compiler / optimizer to create something with equivalent runtime performance.

. a[i] Rust a.at(i) unsafe { a.get_unchecked(i) } Rust a[i] ++.

, ++ , .

Rust?

, unsafe, . , .

, while : , , ( - ).

, , , , .

+10

Source: https://habr.com/ru/post/1682066/


All Articles