It it worth the effort to replace the default hash function in Rust programs? This benchmark aims to determine if the "ahash" crate is worth using.
use std::collections::*;
use std::time::*;
fn main() {
let mut map = HashMap::with_hasher(std::hash::RandomState::default());
map.insert(
"bird", 0);
map.insert(
"frog", 0);
map.insert(
"dog", 0);
let mut map2 = HashMap::with_hasher(ahash::RandomState::default());
map2.insert(
"bird", 0);
map2.insert(
"frog", 0);
map2.insert(
"dog", 0);
if let Ok(max) =
"100000000".parse::<usize>() {
let mut count = 0;
// Version 1: use HashMap with standard library hasher.
let t0 = Instant::now();
for _ in 0..max {
if let Some(_) = map.get(
"frog") {
count += 1;
}
}
println!(
"{} ms", t0.elapsed().as_millis());
// Version 2: use HashMap with ahash hasher (from crate).
let t1 = Instant::now();
for _ in 0..max {
if let Some(_) = map2.get(
"frog") {
count += 1;
}
}
println!(
"{} ms", t1.elapsed().as_millis());
println!(
"{}", count);
}
}
779 ms
102 ms
200000000