Sub topic 16
Choosing between Vec, HashMap and BTreeMap
This chapter assumes you can create and update a Vec<T> and a HashMap<K, V>, and that you know what Eq and Hash mean for keys. Here you will pick a collection by looking at how your program reads its data.
Start with the access pattern
Ask how you will mostly read the data:
- By position, or in the order you added it: use
Vec. - By exact key, with no order needed: use
HashMap. - By key, in sorted order or by range of keys: use
BTreeMap.
BTreeMap<K, V> is in std::collections. It keeps its keys sorted and needs K: Ord instead of Eq + Hash.
Comparing the three
| Need | Vec | HashMap | BTreeMap |
|---|---|---|---|
| Lookup cost | O(1) by index, O(n) by value | O(1) on average | O(log n) |
| Iteration order | Insertion order | Unspecified | Sorted by key |
| Range queries | Slices by index | No | `range` |
| Key requirement | None (index is `usize`) | `Eq + Hash` | `Ord` |
| Memory layout | One contiguous block | Hash table | Tree of nodes |
A Vec is also the fastest to iterate, because its elements sit next to each other in memory. For a few dozen items, a Vec searched with iter().find is often as fast as a map, and it is simpler.
A sorted example
Suppose you store names by age and want everyone in an age range. A HashMap would force you to scan every entry. A BTreeMap walks only the matching part.
use std::collections::BTreeMap;
fn main() {
let mut by_age: BTreeMap<u32, &str> = BTreeMap::new();
by_age.insert(41, "Cy");
by_age.insert(30, "Ana");
by_age.insert(25, "Bo");
// Iteration is always in ascending key order.
for (age, name) in &by_age {
println!("{age}: {name}");
}
// 25: Bo
// 30: Ana
// 41: Cy
// Only entries with 26 <= age <= 41.
for (age, name) in by_age.range(26..=41) {
println!("in range {age}: {name}");
}
// in range 30: Ana
// in range 41: Cy
println!("{:?}", by_age.first_key_value()); // Some((25, "Bo"))
}BTreeMap has the same insert, get, remove and entry methods as HashMap. Switching between the two is usually a change to the type name and the key bounds.
Common mistakes
- Relying on
HashMapiteration order. It can differ between runs. Sort the pairs first, as in the word-count example, or useBTreeMap. - Using a
HashMapfor a small, fixed set of items. AVecof pairs or structs is often clearer. - Using a
Vecand callingcontainsoriter().positioninside a loop. This is O(n) per call and makes the loop O(n²). Build aHashMaporHashSetfirst. - Using
f64as a key. It implements neitherEq,HashnorOrd, so neither map accepts it directly.
Exercise
You need to print the 10 most recent log timestamps in order, and you also need to find the log entries between two given timestamps. Which collection fits, and why not a HashMap?
Show answer
A BTreeMap keyed by timestamp. It keeps keys sorted, so the latest entries are at the end (for example with iter().rev().take(10)), and range(start..=end) returns the entries between two timestamps without scanning all of them. A HashMap has no order and no range query, so you would have to collect and sort the keys each time.