IceGuye Blog

In Rust, How For-Loop Faster Than While-Loop, and How It Does Not

In Rust, sometime for-loop is faster than while-loop, but sometime it is not.

First of all, In Rust, the codes below

let a = [1, 2, 3, 4, 5];
let mut i = 0;
while i < 5 {
    println!("the value is: {}", a[i]);

    i += 1;
}

may be slower because the a[i] is actually a.at(i). And the at() method requires bounds-check, and in Rust bounds-check is one of the few cases which need a runtime check, so it is considered that it may slow down to the same level of most other programming languages with a garbage collector.

In this specific case, to achieve the same performance as C/C++, an unsafe will need to be introduced, so the a[i] will become unsafe { a.get_unchecked(i) }.

For loop will be faster only in cases of iter:

let a = [1, 2, 3, 4, 5];

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

However, this iter will not mutably access the slice, which is required in these cases.

Second, for-loop doesn't always reduce the "variable" and "calculation". In the codes

    for i in 0..128 {
        notes[i] = Some(Note::new(i));
    }

the 0..128 is a Range struct with 128 usize values, similar to a slice. Rust will iter this Range and assign them one-by-one to the i. The i is variable, and the Range also contains many values that waiting to be iterated. This doesn't meet the intention of reducing variable and calculation.




Back to Blog's index