The clippy tool recommends using skip and take instead of for-range loops. But does this improve performance? We test skip and take performance here.
use std::time::*;
fn main() {
if let Ok(max) =
"20000".parse() {
if let Ok(offset) =
"20".parse::<usize>() {
let top_offset = max - offset;
// Sample vector.
let mut source = vec![];
for _ in 0..max {
source.push(0);
}
source[5000] = 1;
let mut sum1 = 0;
let mut sum2 = 0;
// Version 1: range loop.
let t0 = Instant::now();
for _ in 0..max {
for i in offset..top_offset {
if source[i] == 1 {
sum1 += 1;
}
}
}
println!(
"{}", t0.elapsed().as_millis());
// Version 2: take and skip.
let t1 = Instant::now();
for _ in 0..max {
for element in source.iter().take(top_offset).skip(offset) {
if *element == 1 {
sum2 += 1;
}
}
}
println!(
"{}", t1.elapsed().as_millis());
println!(
"{} = {}", sum1, sum2);
}
}
}
222
249
20000 = 20000