use std::time::Instant;
fn main() {
let mut a: Vec<u64> = Vec::with_capacity(1_000_000);
let mut b: [u64; 1_000_000] = [0; 1_000_000];
let mut now = Instant::now();
for i in 1..1_000_001 {
a.push(i * 8);
}
let x1 = now.elapsed();
println!("{:?}", x1);
now = Instant::now();
for i in 1..1_000_001 {
b[i as usize - 1] = i * 8;
}
let x2 = now.elapsed();
println!("{:?}", x2);
std::mem::drop(a);
a = Vec::new();
b = [0; 1_000_000];
now = Instant::now();
for i in 1..1_000_001 {
a.push(i << 3);
}
let x3 = now.elapsed();
println!("{:?}", x3);
now = Instant::now();
for i in 1..1_000_001 {
b[i as usize - 1] = i << 3;
}
let x4 = now.elapsed();
println!("{:?}", x4);
}
Output:
12.145943ms
965ns
13.38689ms
941ns
Errors:
Compiling playground v0.0.1 (/playground)
Finished release [optimized] target(s) in 0.77s
Running `target/release/playground`
here, the vector push seems to take a long time compared to stack array. However, the vector is only being pushed to for a specific constant amount. Is there any way to get the compiler to optimize this stuff so that it is at least in the order of microseconds?