How does extend from slice compare to a for-loop with push()? We can time this. Consider this benchmark—it adds a byte vector to a target byte vector in 2 ways.
use std::time::*;
fn main() {
let iterations = 1000000;
// The data we are appending to the slice.
let mut data: Vec<u8> = vec![];
for i in 0..20 {
data.push(i);
}
// Version 1: Use extend_from_slice.
let now = Instant::now();
let mut target = Vec::with_capacity(iterations * data.len());
for i in 0..iterations {
target.extend_from_slice(&data);
}
println!(
"{} ms", now.elapsed().as_millis());
// Version 2: Use for-loop with push.
let now = Instant::now();
let mut target = Vec::with_capacity(iterations * data.len());
for i in 0..iterations {
for x in &data {
target.push(x);
}
}
println!(
"{} ms", now.elapsed().as_millis());
}
18 ms extend_from_slice
82 ms for, push