I need to initialize a vector for a prime sieve. I did this play to see if the iterator way was fast.
use std::ptr;
const VEC_LEN: usize = 10;
#[inline(never)]
fn init1() -> Vec<usize> {
std::iter::repeat(0).take(VEC_LEN).collect::<Vec<_>>()
}
#[inline(never)]
fn init2() -> Vec<usize> {
let mut v = Vec::with_capacity(VEC_LEN);
unsafe {
let mut p = v.as_mut_ptr();
for _ in 0..VEC_LEN {
ptr::write(p, 0);
p = p.offset(1);
}
v.set_len(VEC_LEN);
}
v
}
fn main() {
println!("{:?}", init1());
println!("{:?}", init2());
}
There seems to be some significant differences between the asm for the 2 methods. Does this mean that my unsafe way is quicker? Is it possible for the compiler to optimize the iterator way to match the unsafe way?