Does calling the any() function cause any slowdown in Rust programs? This can be quickly tested in an example benchmark program.
use std::time::*;
fn main() {
if let Ok(max) =
"10000".parse::<usize>() {
let mut count = 0;
let mut values = vec![];
for _ in 0..1000 {
values.push(
"?");
}
values[500] =
"X";
// Version 1: use any.
let t0 = Instant::now();
for _ in 0..max {
if values.iter().any(|&e| e ==
"X") {
count += 1;
}
}
println!(
"{} ms", t0.elapsed().as_millis());
// Version 2: use for-loop with break.
let t1 = Instant::now();
for _ in 0..max {
for &v in &values {
if v ==
"X" {
count += 1;
break;
}
}
}
println!(
"{} ms", t1.elapsed().as_millis());
println!(
"{count}");
}
}
4 ms any
4 ms for, break
20000