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?
source
share