Suppose we want to loop over a slice of u8 bytes, and find a specific pattern of bytes in the slice. We could use chained if-checks on individual bytes.
use std::time::*;
fn main() {
// The data to test.
let mut data = vec![];
for _ in 0..1000000 {
data.push(0);
data.push(10);
data.push(20);
data.push(30);
}
let mut count1 = 0;
let mut count2 = 0;
// Version 1: use slice-based test.
let t0 = Instant::now();
for _ in 0..1000 {
for i in 3..data.len() {
let slice_here = &data[i - 3..=i];
if slice_here == [0, 10, 20, 30] {
count1 += 1;
}
}
}
println!(
"{}", t0.elapsed().as_millis());
// Version 2: Use individual index tests.
let t1 = Instant::now();
for _ in 0..1000 {
for i in 3..data.len() {
if data[i - 3] == 0 && data[i - 2] == 10 && data[i - 1] == 20 && data[i] == 30 {
count2 += 1;
}
}
}
println!(
"{}", t1.elapsed().as_millis());
println!(
"{} {}", count1, count2);
}
2550 ms (slice equals)
2834 ms
1000000000 1000000000