Another function we can use in Rust is called transmute_copy—this directly casts byte data into a structure. Transmute_copy() is unsafe and should be avoided.
use std::time::*;
use std::mem;
fn main() {
if let Ok(max) =
"200000000".parse() {
let data: Vec<u8> = vec![10, 0, 20, 0, 30, 0, 40, 0, 50, 0];
// Version 1: use from_ne_bytes.
let t0 = Instant::now();
let mut count = 0;
for i in 0..max {
let start = i % 4;
let first = u32::from_ne_bytes(data[start..start+4].try_into().unwrap());
if first == 0 {
count += 1;
}
}
println!(
"{} ms", t0.elapsed().as_millis());
// Version 2: use transmute_copy.
let t0 = Instant::now();
for i in 0..max {
unsafe {
let start = i % 4;
let first = mem::transmute_copy::<[u8; 4], u32>(data[start..start+4].try_into().unwrap());
if first == 0 {
count += 1;
}
}
}
println!(
"{} ms", t0.elapsed().as_millis());
println!(
"{}", count);
}
}
83 ms from_ne_bytes
62 ms transmute_copy
0