Performance Patterns
Hash Map Lookup
Cache Values by Key
A hash map stores values by key so repeated lookups do not need a linear scan.
Program
Play the program to choose a user id and see the cached credit value returned.
hash_map_lookup.rs
use std::collections::HashMap;
fn main() {
let user_id = ;
let mut credits = HashMap::new();
credits.insert(1, 10);
credits.insert(2, 25);
let total = lookup_credit(&credits, user_id);
println!("user {user_id}: {total}");
}
fn lookup_credit(credits: &HashMap<i32, i32>, user_id: i32) -> i32 {
credits.get(&user_id).copied().unwrap_or(0)
}
use std::collections::HashMap;
fn main() {
let user_id = ;
let mut credits = HashMap::new();
credits.insert(1, 10);
credits.insert(2, 25);
let total = lookup_credit(&credits, user_id);
println!("user {user_id}: {total}");
}
fn lookup_credit(credits: &HashMap<i32, i32>, user_id: i32) -> i32 {
credits.get(&user_id).copied().unwrap_or(0)
}
use std::collections::HashMap;
fn main() {
let user_id = ;
let mut credits = HashMap::new();
credits.insert(1, 10);
credits.insert(2, 25);
let total = lookup_credit(&credits, user_id);
println!("user {user_id}: {total}");
}
fn lookup_credit(credits: &HashMap<i32, i32>, user_id: i32) -> i32 {
credits.get(&user_id).copied().unwrap_or(0)
}
hash map
`HashMap` stores values under keys for direct lookup.
copied
`copied()` turns an `Option<&i32>` into an `Option<i32>` for this small value type.
fallback
`unwrap_or(0)` supplies a default when a key is not cached.