A Rust game loop profile shows SipHash dominating lookups in a `HashMap<u64, Entity>` keyed by engine-assigned IDs; how do you swap the hasher, and what changes?
answer
- the third type parameter
- BuildHasher builds the Hasher
- new() is RandomState-only
- who chooses the keys
basics
~10 sSet HashMap's third type parameter to a faster BuildHasher, such as rustc-hash's FxBuildHasher, and build maps with default() or with_hasher; HashMap::new stops applying, and functions taking HashMap<K, V> must become generic over S: BuildHasher.
solid answer
~40 s`HashMap<K, V, S = RandomState>` takes its hasher factory as a type parameter, so `FxHashMap<u64, Entity>` from the `rustc-hash` crate is still std's map with `S = FxBuildHasher`. Build it with `FxHashMap::default()`, `with_hasher` or `with_capacity_and_hasher`, or `collect()`; `HashMap::new()` and `HashMap::from([...])` are defined only for `RandomState` and give E0308 or the wrong type. Any function taking `&HashMap<u64, Entity>` now rejects the map with E0308 until it is made generic as `fn f<S: BuildHasher>(m: &HashMap<u64, Entity, S>)`. It is safe here because players never choose the ids: `FxBuildHasher` is unkeyed, so attacker-chosen keys could be made to collide. `BuildHasherDefault<DefaultHasher>` is no speed fix; it is still SipHash, with fixed keys. Benchmark before and after.
code
rust · 23 linesuse rustc_hash::{FxBuildHasher, FxHashMap};
use std::collections::HashMap;
use std::hash::BuildHasher;
// Generic over the map's third type parameter: accepts any hasher.
fn total_hp<S: BuildHasher>(hp: &HashMap<u64, u32, S>) -> u32 {
hp.values().sum()
}
fn main() {
// entity id -> hit points; ids are assigned by the engine, never by a player
let mut hp: FxHashMap<u64, u32> = FxHashMap::default();
hp.insert(1, 100);
hp.insert(2, 80);
let mut pre_sized: HashMap<u64, u32, FxBuildHasher> =
HashMap::with_capacity_and_hasher(1024, FxBuildHasher);
pre_sized.insert(3, 50);
let std_map: HashMap<u64, u32> = HashMap::from([(4, 10)]);
println!("{} {} {}", total_hp(&hp), total_hp(&pre_sized), total_hp(&std_map));
}go deeper
Know that HashMap's hashing algorithm can be changed and that the default favours safety over raw speed.
Explain the S type parameter, BuildHasher versus Hasher, and why HashMap::new only builds RandomState maps.
Perform the swap end to end: alias the type, construct with default or with_hasher, make boundary functions generic over S, justify safety by key provenance, and prove the gain with a release-mode benchmark.
Judge whether one hot map justifies a dependency and a second map type in the codebase. Keep such swaps local, named and reversible, and tie them to the rule on which keys outsiders control.
## The hasher is a type parameter `std::collections::HashMap` has three type parameters you can name: `HashMap<K, V, S = RandomState>`. (A fourth, the allocator, is unstable.) `S` must implement **`BuildHasher`**, a factory with one required method, `build_hasher(&self) -> Self::Hasher`, whose `Hasher` does the actual hashing. The default, `RandomState`, builds SipHash 1-3 hashers with random keys. std's documentation is candid about the cost: SipHash is "very competitive for medium sized keys", but other algorithms "will outperform it for small keys such as integers as well as large keys such as long strings", and those algorithms "will typically *not* protect against attacks such as HashDoS". A game loop that looks entities up by `u64` ids assigned by the engine is the textbook case where the trade is worth considering: the keys are small integers and no player chooses them. ## Swapping the hasher The `rustc-hash` crate (the hasher the Rust compiler itself uses) provides `FxBuildHasher` and the alias `FxHashMap<K, V> = HashMap<K, V, FxBuildHasher>`. The map is still std's `HashMap`; only `S` changes. Ways to build one: - `FxHashMap::default()`, which works because `HashMap<K, V, S>: Default` when `S: Default`. - `HashMap::with_hasher(FxBuildHasher)`. - `HashMap::with_capacity_and_hasher(1024, FxBuildHasher)` for a pre-sized map. - `.collect()`: `FromIterator` is implemented for any `S: BuildHasher + Default`. Sets work the same way: `HashSet<T, S = RandomState>`, with `rustc-hash` providing `FxHashSet<T> = HashSet<T, FxBuildHasher>`. std's own documentation shows one more use of a key-free hasher: building a map in a `const` or `static` initializer, which `RandomState` cannot support because its keys come from the OS at run time. It attaches the same warning: such a map is not resistant to HashDoS attacks. ## What stops compiling Changing `S` changes the **type**, and several conveniences are written only for `RandomState`. | Code | Why it fails or changes | Fix | |---|---|---| | `let m: FxHashMap<u64, u32> = HashMap::new();` | `new` and `with_capacity` exist only on `HashMap<K, V, RandomState>`; **E0308** | `default()` or `with_hasher` | | `HashMap::from([(1, 2)])` | the `From<[(K, V); N]>` impl is for `RandomState` only | `collect()` | | `fn total(m: &HashMap<u64, u32>)` called with an Fx map | the parameter means `RandomState`; **E0308** | `fn total<S: BuildHasher>(m: &HashMap<u64, u32, S>)` | | struct fields and return types | they spell the old type | use the alias consistently | std's source explains the `From` choice: it keeps `HashMap::from([...])` usable without a type annotation, and points users who want a hasher to `with_capacity_and_hasher`. Clippy's pedantic, allow-by-default `implicit_hasher` lint flags public functions that hard-code the default hasher instead of being generic over `S`. ## Why it is safe here, and when it is not 1. **Key provenance.** HashDoS needs an attacker who can choose many keys that collide. Engine-assigned ids give no one that power. A map keyed by player names, chat words or network-supplied ids would. 2. **What `FxBuildHasher` is.** It is a unit struct whose `build_hasher` returns `FxHasher::default()`, so the hash has **no key**: it is the same on every run, and anyone can compute it offline to search for colliding inputs. 3. **Not a speed fix: `BuildHasherDefault<DefaultHasher>`.** That still runs SipHash 1-3, only with the fixed keys `(0, 0)` that `DefaultHasher::new()` uses. It gives determinism (useful for a `const` or `static` map, as std's docs show) and no speed gain. 4. **The `BuildHasher` contract.** Each call to `build_hasher` on the same instance should produce identical hashers. A custom implementation that breaks this hashes a key differently at insert and at lookup, and lookups then miss keys that are present. ## Verify the win - Benchmark the real lookup path with realistic keys and sizes before and after, in release mode; how to benchmark reliably is covered with performance measurement. - Check that hashing, not cache misses or the work done per entity, was the bottleneck: a faster hash does not fix a map that is simply too large for cache. - Keep the change local: an alias at the map's definition and generic functions at its boundaries, so reverting is one line. - Write down why the keys are safe next to the alias, so the next person who starts filling the map from network input sees the assumption they are about to break.
- Why not use `BuildHasherDefault<DefaultHasher>` instead of adding a crate?Because it is not faster. `DefaultHasher::new()` is SipHash 1-3 with keys fixed at zero, so the map does the same hashing work as `RandomState` and only loses the random keys. Its real uses are determinism and building a map in a `const` or `static`, which std's docs show, and std warns such a map is not HashDoS-resistant.
- How should a library expose functions so callers can pick their own hasher?Make them generic over the hasher: `pub fn index<S: BuildHasher>(m: &HashMap<String, u32, S>)`. Add `+ Default` only if the function creates maps. Clippy's pedantic `implicit_hasher` lint, allow-by-default, points out public functions that hard-code `HashMap<K, V>` and so silently mean `RandomState`.
- What does a custom `BuildHasher` have to guarantee?std's documentation for `build_hasher` says every call on the same instance should produce identical `Hasher`s. The map hashes a key at insert time and again at every lookup, so a builder that varied between calls would send the same key to different buckets and lookups would miss. Per-map randomness belongs in the builder's state, fixed when the builder is created, as `RandomState` does.
- HashMap::new() works for any hasher type once the variable is annotated
- A faster hasher is always safe because a hash map is an internal detail
- BuildHasherDefault<DefaultHasher> is a faster hasher than RandomState
- Changing the hasher does not change the map's type
- A function taking &HashMap<K, V> accepts an FxHashMap through coercion