Suppose we have a function that would use the contains() function many times. Does this cause any performance problem in Rust?
use std::time::*;
fn test_contains(value: i32) -> usize {
if (10..=20).contains(&value) {
return 1;
}
if (50..=100).contains(&value) {
return 2;
}
0
}
fn test_if(value: i32) -> usize {
if value >= 10 && value <= 20 {
return 1;
}
if value >= 50 && value <= 100 {
return 2;
}
0
}
fn main() {
if let Ok(max) =
"20000000".parse() {
let mut sum1 = 0;
let mut sum2 = 0;
// Version 1: contains.
let t0 = Instant::now();
for i in 0..max {
sum1 += test_contains(i as i32);
}
println!(
"{}", t0.elapsed().as_millis());
// Version 2: if.
let t1 = Instant::now();
for i in 0..max {
sum2 += test_if(i as i32);
}
println!(
"{}", t1.elapsed().as_millis());
println!(
"{} = {}", sum1, sum2);
}
}
10 ms (contains)
10 ms
113 = 113