Surprised by the benchmark about iter fold and for loop
https:\/\/github.com\/mike-barber\/rust-zero-cost-abstractions
I'm surprised by the benchmark about iter fold and for loop, both of which use zip and mutate a variable:
// 3.66 μs
pub fn calculate_fold(slice_a: &[i32], slice_b: &[i32]) -> i64 {
slice_a
.iter()
.zip(slice_b.iter())
.fold(0_i64, |acc, (a, b)| match *a > 2 {
true => acc + (*a as i64 * *b as i64),
false => acc,
})
}
// 6.6 μs: 1.83x slower than fold
pub fn calculate_direct(slice_a: &[i32], slice_b: &[i32]) -> i64 {
let mut res = 0;
for (a, b) in slice_a.iter().zip(slice_b.iter()) {
if *a > 2 {
res += *a as i64 * *b as i64;
}
}
res
}
So what matters here? Is fold method preferred to for loops wrt iterators? I remember for var in iter is a zero-cost-abstraction. Did I misremember that?