Sub topic 16
Choosing between Vec, HashMap and BTreeMap
This chapter assumes you can create a Vec and a HashMap, use get and the entry API, and read Option results with match. It also assumes you know what Eq and Hash mean for keys. Here you will pick one collection for a task by looking at how the program uses the data.
Start from the access pattern
The type that stores your data matters less than the questions you ask of it. Ask these first:
- Do I look items up by position, or by a key?
- Do I need to walk the items in a defined order?
- Do I need "everything between A and B", or "the smallest" and "the largest"?
- How many items will there be?
| Operation | `Vec<T>` | `HashMap<K, V>` | `BTreeMap<K, V>` |
|---|---|---|---|
| Read by index | O(1) | not available | not available |
| Find by key or value | O(n) unsorted, O(log n) sorted | O(1) average | O(log n) |
| Add at the end | O(1) amortized | not applicable | not applicable |
| Insert by key | O(n) in the middle | O(1) average | O(log n) |
| Remove | O(n) except the last item | O(1) average | O(log n) |
| Iteration order | insertion order | unspecified | sorted by key |
| Range queries | slice of a sorted Vec | no | `range` |
| Key requirements | none | `Eq + Hash` | `Ord` |
"Amortized" means occasional reallocations are averaged across many pushes. "Average" for HashMap means that a bad hash function or an adversarial input could make individual operations slower.
The same data in three collections
The following program stores three fruit prices in each collection and looks one up.
use std::collections::{BTreeMap, HashMap};
fn main() {
let pairs = [("pear", 4), ("apple", 3), ("fig", 9)];
let list: Vec<(&str, i32)> = pairs.to_vec();
let found = list.iter().find(|(k, _)| *k == "fig");
println!("{:?}", found); // Some(("fig", 9))
let hash: HashMap<&str, i32> = pairs.into_iter().collect();
println!("{:?}", hash.get("fig")); // Some(9)
let tree: BTreeMap<&str, i32> = pairs.into_iter().collect();
println!("{:?}", tree); // {"apple": 3, "fig": 9, "pear": 4}
}The Vec finds "fig" by scanning every pair. The HashMap jumps to it through its hash. The BTreeMap descends a balanced tree and prints in key order without any extra sorting. Printing the HashMap instead could show the entries in a different order on each run.
When a Vec is the right answer
A Vec is the default. Reach for something else only when the access pattern calls for it.
- Small collections. For a few dozen items, a linear scan over contiguous memory is often as fast as a hash lookup or faster. The scan stays in the CPU cache and does no hashing.
- Order matters, or duplicates are allowed. A
HashMaporBTreeMapholds one value per key. AVeckeeps every item, in the order you added it. - Mostly iterating. If you process every item and rarely search, a
Vechas the lowest overhead. - Sorted data with occasional lookups. Sort once, then use
binary_search.
fn main() {
let ids = vec![2, 5, 9, 14, 20];
println!("{:?}", ids.binary_search(&9)); // Ok(2)
println!("{:?}", ids.binary_search(&10)); // Err(3)
}binary_search returns Ok(index) when it finds the value. Otherwise it returns Err(index), where index is the position that would keep the Vec sorted. It gives meaningless results if the Vec is not sorted, and the compiler cannot check that for you.
The usual mistake is calling contains or iter().position(...) inside a loop over another large Vec. That is O(n × m). Build a HashMap (or a HashSet) from one side first, and the loop becomes O(n + m).
When a HashMap is the right answer
Use a HashMap when you look items up by key, you do not care about order, and the collection is large enough that scanning would be slow. Typical uses are counting, grouping, caching and indexing records by ID, all of which the entry API handles in one lookup.
Keep these points in mind:
- Iteration order is unspecified and can change between runs. Never let program output depend on it. If you must print the contents, collect them into a
Vecand sort it, as the word-count example in the entry API chapter did. - Keys need
EqandHash. Floating-point typesf32andf64implement neither, becauseNaN != NaN. Use an integer, a string, or a wrapper that converts the float to a well-defined form such as its bit pattern. - Mutating a key's contents while it is in the map is impossible in safe Rust, since the map owns the key and gives out only shared references to it.
- The default hasher, SipHash, is designed to resist hash-flooding attacks. It is not the fastest hasher available. If profiling shows hashing is a bottleneck and the keys are not attacker-controlled, a custom hasher can help. Do not switch before you measure.
When a BTreeMap is the right answer
A BTreeMap keeps keys sorted. Choose it when order is part of the requirement.
use std::collections::BTreeMap;
fn main() {
let mut events: BTreeMap<u32, &str> = BTreeMap::new();
events.insert(900, "standup");
events.insert(1300, "lunch");
events.insert(1500, "review");
events.insert(1700, "close");
for (time, name) in events.range(1000..1600) {
println!("{time} {name}");
}
// 1300 lunch
// 1500 review
println!("{:?}", events.first_key_value()); // Some((900, "standup"))
println!("{:?}", events.last_key_value()); // Some((1700, "close"))
}The map was filled out of order, yet range visits only the keys in 1000..1600, in ascending order. A HashMap cannot do this. It would have to scan every entry and sort the matches afterward.
Use BTreeMap for these jobs:
- Reports and output that must be in key order, with no separate sort step.
- Range queries such as "all events between 10:00 and 16:00".
- Smallest and largest keys, through
first_key_valueandlast_key_value. - Deterministic behavior. Two runs with the same inserts always iterate identically, which makes tests and logs easier to compare.
The cost is that keys need Ord, and every operation is O(log n) instead of O(1) on average. For most programs that difference is invisible. The tree also stores entries in many small nodes rather than one flat table, but it never has to rehash everything when it grows.
The entry API works on BTreeMap in the same way as on HashMap. Code that counts or groups with entry(...).or_insert(...) can move between the two by changing the type name, as long as the key type implements Ord.
Common errors
- Using a
HashMapwhere aVecindexed by a small integer would do. If keys are0..nwith few gaps,Vec<T>orVec<Option<T>>is simpler and faster. - Expecting a stable order from a
HashMap. A test that passes once and fails on the next run usually has this bug. - Using an unsorted
Vecwithbinary_search. The call compiles and returns a wrong answer. - Deriving only some traits on a key type. A struct used in a
HashMapneedsPartialEq,EqandHash. A struct used in aBTreeMapneedsPartialEq,Eq,PartialOrdandOrd. Derive them together. - Choosing by habit rather than evidence. If performance is the concern, measure with realistic data sizes before replacing a simple
Vec.
Summary of the decision
| Situation | Choice |
|---|---|
| Sequence of items, duplicates allowed, order of insertion matters | `Vec` |
| Few items, occasional search | `Vec` with `iter().find` |
| Sorted items, repeated lookups | sorted `Vec` with `binary_search` |
| Lookup, counting or grouping by key at scale | `HashMap` |
| Key order, ranges, min or max by key, deterministic output | `BTreeMap` |
Exercise
A program stores about 200,000 log entries, each with a timestamp as a u64 key and a message. The program must (a) add entries as they arrive, in no particular timestamp order, and (b) print every entry whose timestamp falls between two given values, in ascending order. Which collection do you choose, and why not the other two?
Show answer
Use BTreeMap<u64, String>. Its range method returns exactly the entries in a key interval, already in ascending order, and each insert costs O(log n) regardless of arrival order. A HashMap would need a scan of all 200,000 entries plus a sort for every query, because it has no order. A Vec would need an O(n) insert to keep it sorted, or a sort after each batch of inserts. Appending to an unsorted Vec is cheap, but then every range query must scan the whole Vec and sort the matches. If timestamps can repeat, store a Vec<String> as the value, since a map keeps one value per key.
Exercise
This code finds which of 50,000 orders have a customer_id present in a list of 50,000 vip_ids (both Vec<u32>). It uses vip_ids.contains(&order.customer_id) inside a loop. What is the problem, and what is the fix?
Show answer
Each contains call scans up to 50,000 items, so the loop does up to 50,000 × 50,000 comparisons, which is O(n × m). Build a lookup structure from vip_ids once, for example a HashSet<u32> made with vip_ids.into_iter().collect(), and call contains on the set. Each check is then O(1) on average, and the whole job is O(n + m). Sorting vip_ids once and calling binary_search also works, at O(log m) per check.