I'm trying to understand why for_each
performs much faster than a for .. in
in my code. Even though the official docs say that the performance should be more or less the same. - https://doc.rust-lang.org/book/ch13-04-performance.html
Here is my code, it just sums up a given number:
fn main() {
let arg1 = std::env::args().nth(1).expect("no arg given");
let number = arg1.parse::<i128>().unwrap();
println!("{number}");
let mut result = 0;
(1..=number).for_each(|n| result += n);
println!("{result}")
}
When I replace the for_each
with the following for loop, it's much slower with big numbers:
for n in 1..=number {
result += n;
}
Timings are tested with time cargo run -r 1000000000
.