Does fill() perform faster compared to a for-loop? Sometimes functions that act upon many elements at once are more optimized.
use std::time::*;
fn main() {
// Data to fill.
let mut array = [0; 15];
if let Ok(max) =
"10000".parse::<usize>() {
// Version 1: use fill.
let t0 = Instant::now();
let mut sum = 0;
for _ in 0..max {
for i in 0..max {
array.fill(5);
}
}
println!(
"{} ms", t0.elapsed().as_millis());
// Version 2: use for-loop.
let t1 = Instant::now();
for _ in 0..max {
for i in 0..max {
for q in 0..array.len() {
array[q] = 5;
}
}
}
println!(
"{} ms", t1.elapsed().as_millis());
println!(
"{}", array[0]);
}
}
783 ms fill()
781 ms
5