Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

IndexMap: Rust's Ordered HashMap – Implementation, Benchmarks & Use Cases

This article analyzes IndexMap, a Rust crate providing an insertion-order preserving hash map with HashMap-level lookup performance and significantly faster iteration, covering its API, internal design using a dense entry vector plus hash index, benchmark results against HashMap and BTreeMap, and practical use cases like deterministic serialization and order-book queues.

Problem: HashMap's Unstable Iteration Order

Rust's standard HashMap uses RandomState by default, generating a new random hash seed per instance. Identical insertion sequences produce different iteration orders across runs:

let mut m = HashMap::new();
for s in ["AAPL", "MSFT", "NVDA", "TSLA", "AMZN"] {
    m.insert(s, 0);
}
println!("{:?}", m.keys().collect::<Vec<_>>());

Three consecutive runs yield:

["TSLA", "MSFT", "AMZN", "AAPL", "NVDA"]
["TSLA", "MSFT", "AAPL", "AMZN", "NVDA"]
["NVDA", "AMZN", "AAPL", "MSFT", "TSLA"]

This non-determinism breaks reproducible backtests (event publish order changes, affecting seeded RNG consumption), makes serialized JSON diffs impossible, and forces tests to sort before comparing.

Common Workarounds and Their Drawbacks

Sort before iterating : O(n log n) allocation per traversal; yields key order, not insertion order.

Use BTreeMap : Fixed key order but O(log n) lookup, much slower than hash tables.

HashMap + Vec for order : Manual sync required; deletion needs linear search in the Vec. IndexMap adopts the third approach but maintains both structures internally: data stored in insertion order in a Vec (traversal = array scan), hash table stores only indices into that Vec for O(1) key lookup. Deletion achieves O(1) via swap-with-last.

IndexMap Usage (indexmap = "2")

Basic API

API mirrors HashMap; iteration follows insertion order:

use indexmap::IndexMap;
let mut m = IndexMap::new();
for s in ["AAPL", "MSFT", "NVDA", "TSLA", "AMZN"] {
    m.insert(s, 0);
}
println!("{:?}", m.keys().collect::<Vec<_>>());
// ["AAPL", "MSFT", "NVDA", "TSLA", "AMZN"]

m.insert("MSFT", 1); // key exists: updates value, position unchanged
println!("{:?}", m);
// {"AAPL": 0, "MSFT": 1, "NVDA": 0, "TSLA": 0, "AMZN": 0}

Each element has a continuous index 0..len():

m.get_index_of("NVDA"); // Some(2)
m.get_index(1);         // Some(("MSFT", 1))
m.first();              // Some(("AAPL", 0))
m.insert_full("META", 7); // (5, None) returns new index and old value

API Differences from HashMap

get_index(i)

/ map[i] — Access by index — O(1) get_index_of(&k) / get_full(&k) — Lookup key, return index too — O(1) insert_full(k, v) — Insert, return index — O(1) first() / last() / pop() — Access/remove ends — O(1) swap_remove(&k) — Remove, last element fills gap — O(1) shift_remove(&k) — Remove, shift subsequent elements left — O(n) shift_insert(i, k, v) — Insert at specific position — O(n) move_index(from, to) — Move element — O(n) swap_indices(a, b) — Swap two positions — O(1) sort_keys() / sort_by(..) — Reorder by key or custom fn — O(n log n) retain(..) — Filter in place, keep order — O(n) map[i] with usize returns value; map[&k] with key also returns value. sort_keys is a one-time reorder; subsequent inserts still append. For permanently key-sorted maps, use BTreeMap.

Deletion Semantics

// m: AAPL, MSFT, NVDA, TSLA, AMZN
a.swap_remove("MSFT"); // AAPL, AMZN, NVDA, TSLA
b.shift_remove("MSFT"); // AAPL, NVDA, TSLA, AMZN
swap_remove

: Like Vec::swap_remove, moves last element into the gap. O(1) but order disrupted; only the moved element's index changes. shift_remove: Like Vec::remove, shifts later elements left. Preserves order, O(n); all indices after the gap decrement by 1. remove behaves like swap_remove and is deprecated with note: " remove disrupts the map order -- use swap_remove or shift_remove for explicit behavior." External cached indices may be invalidated by either method.

Custom Hasher

IndexMap<K, V, S = RandomState>

accepts a hasher like HashMap. Default RandomState uses SipHash (randomized, DoS-resistant but slower). For trusted keys (internal integers, contract codes), faster hashers help:

use rustc_hash::FxBuildHasher;
pub type FxIndexMap<K, V> = indexmap::IndexMap<K, V, FxBuildHasher>;
pub type FxIndexSet<T> = indexmap::IndexSet<T, FxBuildHasher>;
let mut m: FxIndexMap<u64, Order> = FxIndexMap::default();
ahash

, foldhash are also common. Construction must use default() or with_hasher(); new() only works for default RandomState. Fixed-seed hashers make HashMap iteration reproducible but still dependent on hash values and mutation history; IndexMap order depends solely on operation sequence. Keep RandomState for untrusted external input.

IndexSet

IndexSet<T>

wraps IndexMap<T, ()> for deduplication preserving first-occurrence order, supporting get_index, swap_remove, shift_remove.

Features

std

(default) — Provides RandomState; disable for no_std (must supply hasher) serde — Serialize/deserialize in insertion order rayon — Parallel iteration

Source Code Analysis

Data Structure

pub struct IndexMap<K, V, S = RandomState> {
    pub(crate) core: Core<K, V>,
    hash_builder: S,
}

pub(crate) struct Core<K, V> {
    /// indices mapping from the entry hash to its index.
    indices: hash_table::HashTable<usize>,
    /// entries is a dense vec maintaining entry order.
    entries: Vec<Bucket<K, V>>,
}

struct Bucket<K, V> {
    hash: HashValue,
    key: K,
    value: V,
}

Two parts: entries: plain Vec storing key, value, and hash in insertion order, no holes. indices: hash table ( hashbrown::HashTable, same as std HashMap) storing only usize indices into entries. Bucket caches the hash for resize, delete, sort without rehashing. Core is hasher-agnostic; outer IndexMap computes hashes and passes them down.

IndexMap memory layout
IndexMap memory layout
HashMap

stores key-value directly in hash slots (order determined by hash). IndexMap separates "locate by hash" from "store data": hash table maps key → index, data lives in Vec by insertion order. Python 3.6+ dict uses the same layout (compact entries array + sparse indices array), originally for memory savings (empty slots shrink from 24 bytes to 1–8 bytes). Python 3.7 made insertion order a language guarantee. Python leaves holes on deletion (O(1) delete + order preserved) but indices become non-contiguous, losing random-access-by-index. IndexMap keeps entries hole-free, enabling get_index APIs, at the cost of choosing between O(1) unordered delete ( swap_remove) and O(n) ordered delete ( shift_remove).

Lookup

pub fn get_index_of<Q>(&self, key: &Q) -> Option<usize>
where Q: ?Sized + Hash + Equivalent<K>,
{
    match self.as_entries() {
        [] => None,
        [x] => key.equivalent(&x.key).then_some(0),
        _ => {
            let hash = self.hash(key);
            self.core.get_index_of(hash, key)
        }
    }
}

Single element: direct key compare, no hash. Multiple: compute hash, delegate to Core:

pub(crate) fn get_index_of<Q>(&self, hash: HashValue, key: &Q) -> Option<usize>
where Q: ?Sized + Equivalent<K>,
{
    let eq = equivalent(key, &self.entries);
    self.indices.find(hash.get(), eq).copied()
}

fn equivalent<'a, K, V, Q: ?Sized + Equivalent<K>>(
    key: &'a Q,
    entries: &'a [Bucket<K, V>],
) -> impl Fn(&usize) -> bool {
    move |&i| Q::equivalent(key, &entries[i].key)
}
indices

holds only indices; equality function eq receives index i, fetches key from entries[i] for comparison. Hash table probing loads control bytes (16 at a time via SIMD), each slot stores high 7 bits of hash (tag). Only matching tags invoke eq; 128 tag values filter most unequal keys.

Hit lookup comparison: HashMap: read control byte → read slot's key-value → compare key. IndexMap: read control byte → read slot's index → read entries[i] → compare key.

Extra indirection. Small tables fit in cache, difference negligible; large tables exceed cache, extra access plus larger footprint increases cache misses, widening gap. Missed lookups usually end at control-byte layer without touching entries, so similar. Equivalent is more flexible than Borrow: std requires K: Borrow<Q>; IndexMap only needs Q: Equivalent<K> (equality + same hash). Example: key (String, String), query with custom (&str, &str) without allocating String s.

Insertion

pub(crate) fn insert_full(&mut self, hash: HashValue, key: K, value: V) -> (usize, Option<V>)
where K: Eq,
{
    let eq = equal(&key, &self.entries);
    let hasher = get_hash(&self.entries);
    match self.indices.entry(hash.get(), eq, hasher) {
        hash_table::Entry::Occupied(entry) => {
            let i = *entry.get();
            (i, Some(mem::replace(&mut self.entries[i].value, value)))
        }
        hash_table::Entry::Vacant(entry) => {
            let i = self.entries.len();
            entry.insert(i);
            self.push_entry(hash, key, value);
            (i, None)
        }
    }
}

Key exists: replace entries[i].value, position unchanged.

Key absent: new index = current length; write index into hash table; append to entries.

Third argument hasher used during hash table resize to recompute slot positions from cached hashes:

fn get_hash<K, V>(entries: &[Bucket<K, V>]) -> impl Fn(&usize) -> u64 {
    move |&i| entries[i].hash.get()
}

Reads stored hash; index table resize only rearranges indices using cached hashes, no key rehashing. entries resize may move all key-values. For expensive-hash keys like String, avoiding rehash is a win. entries capacity growth aligns with index table:

fn push_entry(&mut self, hash: HashValue, key: K, value: V) {
    if self.entries.len() == self.entries.capacity() {
        self.reserve_entries(1);
    }
    self.entries.push(Bucket { hash, key, value });
}

fn reserve_entries(&mut self, additional: usize) {
    let try_capacity = Ord::min(self.indices.capacity(), Self::MAX_ENTRIES_CAPACITY);
    let try_add = try_capacity - self.entries.len();
    if try_add > additional && self.entries.try_reserve_exact(try_add).is_ok() {
        return;
    }
    self.entries.reserve_exact(additional);
}

When Vec capacity exhausted, tries to grow to index table capacity to reduce future reallocations.

Deletion

swap_remove

removes index from hash table, then handles entries:

fn swap_remove_finish(&mut self, index: usize) -> (K, V) {
    let entry = self.entries.swap_remove(index);
    // correct index that points to the entry that had to swap places
    if let Some(entry) = self.entries.get(index) {
        let last = self.entries.len();
        update_index(&mut self.indices, entry.hash, last, index);
    }
    (entry.key, entry.value)
}

fn update_index(table: &mut Indices, hash: HashValue, old: usize, new: usize) {
    let index = table
        .find_mut(hash.get(), move |&i| i == old)
        .expect("index not found");
    *index = new;
}

Last element moved to index; hash table still points to old last, updated to index. update_index uses cached hash to locate slot, compares index i == old (no key compare). Two hash table lookups + one Vec::swap_remove = O(1). shift_remove uses Vec::remove (O(n)); all subsequent indices in hash table must decrement:

fn decrement_indices(&mut self, start: usize, end: usize) {
    let shifted_entries = &self.entries[start..end];
    if shifted_entries.len() > self.indices.capacity() / 2 {
        // Shift all indices in range.
        for i in &mut self.indices {
            if start <= *i && *i < end {
                *i -= 1;
            }
        }
    } else {
        // Find each entry in range to shift its index.
        for (i, entry) in (start..end).zip(shifted_entries) {
            update_index(&mut self.indices, entry.hash, i, i - 1);
        }
    }
}

Heuristic: if shifted count > half capacity, full scan of hash table; otherwise per-entry find_mut. Deleting near end is cheap; deleting first element is worst case.

Sorting and Retain

Sort operates on entries, then rebuilds hash table:

pub fn sort_keys(&mut self)
where K: Ord,
{
    self.with_entries(move |entries| {
        entries.sort_by(move |a, b| K::cmp(&a.key, &b.key));
    });
}

pub(crate) fn with_entries<F>(&mut self, f: F)
where F: FnOnce(&mut [Bucket<K, V>]),
{
    f(&mut self.entries);
    self.rebuild_hash_table();
}

Rebuild reads cached hashes, no rehash. retain runs Vec::retain_mut on entries, rebuilds hash table only if elements removed.

Performance Advantages and Costs

Fast:

Iteration : sequential scan of contiguous entries, no empty slots. HashMap scans all slots including empties; after mass deletions slot count doesn't shrink, still scans full table.

Lookup on par with HashMap : identical probing (SIMD tag compare), only one extra entries[i] access.

Resize, delete, sort : use cached hashes, avoid rehashing keys.

Index access : get_index is direct Vec indexing.

Costs:

Memory : extra hash table of usize (8 bytes/element) + cached hash per entry.

Large-table lookup : extra indirection; gap widens when table exceeds cache.

Ordered delete is O(n) : must use shift_remove to preserve order.

Benchmarks

Methodology

Machine: Apple M4 Pro.

Tool: criterion.

Keys: random u64; values: 32-byte struct.

Hasher: both HashMap and IndexMap use FxBuildHasher to isolate data-structure differences.

Sizes: 1,000; 100,000; 1,000,000 elements.

Numbers show average time per element per operation.

Insertion (from empty, no reserve)

Size       HashMap   IndexMap   BTreeMap
1,000      11.7 ns   15.4 ns    19.8 ns
100,000    15.2 ns   19.3 ns    89.2 ns
1,000,000  26.1 ns   45.2 ns    178.4 ns

IndexMap insert ~30–75% slower than HashMap (writes two structures, both reallocate on resize). With String keys (e.g., INST-00000001):

Size       HashMap   IndexMap
1,000      14.3 ns   15.6 ns
100,000    19.1 ns   22.2 ns

More expensive key hashing narrows the gap. HashMap rehashes every key on resize; IndexMap reads cached hash.

Lookup (all keys, shuffled, all hits)

Size       HashMap   IndexMap   BTreeMap
1,000      0.87 ns   1.12 ns    7.18 ns
100,000    1.91 ns   2.56 ns    55.6 ns
1,000,000  5.89 ns   11.46 ns   133.6 ns

In-cache: IndexMap ~30% slower; 1M elements: 2× slower. 1M elements exceed cache; extra entries[i] access and larger footprint increase cache misses. Both ~1/6 to 1/29 of BTreeMap. Miss lookups: IndexMap 10–20% slower (1,000 elements slightly faster).

Iteration (sum all values)

Size       HashMap   IndexMap   BTreeMap
1,000      0.53 ns   0.13 ns    0.63 ns
100,000    1.28 ns   0.38 ns    0.66 ns
1,000,000  2.06 ns   0.49 ns    0.67 ns

IndexMap iteration ~¼ of HashMap .

After inserting 1M then deleting 90% (100k left):

HashMap   IndexMap
Iterate once 543 µs    37 µs

HashMap ~15× slower. It still scans 2M+ slots;

IndexMap
entries

only 100k.

Deletion (delete + re-insert to keep size constant; delete index 0 = worst case for shift_remove )

Size       HashMap::remove   IndexMap::swap_remove   IndexMap::shift_remove
1,000      12.0 ns         13.0 ns                 1.13 µs
100,000    13.1 ns         13.2 ns                 156 µs

swap_remove matches HashMap ; shift_remove deleting first element scales linearly.

Memory (counting allocator, average bytes per element after insertion)

Size       HashMap   IndexMap   BTreeMap
1,000      84.0 B    104.5 B    63.1 B
100,000    53.7 B    66.8 B     62.5 B
1,000,000  86.0 B    107.0 B    62.4 B

IndexMap ~25% more than HashMap . Test key-value = 40 bytes. HashMap slot = 40+1 bytes (empty slots count); IndexMap index slot = 8+1 bytes, entries element = 48 bytes. Capacities equal (doubling on resize), load factor 44–87.5%, so per-element average fluctuates. Larger key-values amplify entries no-empty-slot advantage, narrowing gap.

Use Cases

Deterministic Iteration

Backtests/simulations need identical output for identical input. Selection guide:

Iteration order visible externally (event publish, RNG consumption, serialization, logs) → IndexMap / IndexSet Hot path (most frequent, latency-sensitive) only does lookup, order irrelevant → HashMap + fast hasher

Need key-sorted iteration → BTreeMap, or explicit sort at use site

Keys from external input → Keep default

RandomState

Order-Book Queues at a Price Level

Orders at same price queued by time (FIFO). Cancel/modify by order ID; fills consume from front. IndexMap<OrderId, Order> Satisfies both: insertion order = queue order; ID lookup O(1). Cancel uses shift_remove (preserves time priority); swap_remove would move tail order to front, breaking priority.

Consuming a fill from front:

fn consume(queue: &mut IndexMap<OrderId, u64>, mut traded: u64) {
    while traded > 0 {
        let Some((_, &qty)) = queue.first() else { break };
        if qty <= traded {
            queue.shift_remove_index(0);
            traded -= qty;
        } else {
            queue[0] = qty - traded; // partial fill, position unchanged
            traded = 0;
        }
    }
}
shift_remove

O(n) acceptable because orders per price level typically few to dozens. Simulating own-queue-ahead estimation uses same structure: each live order maps to IndexMap<OrderId, u64> tracking preceding orders/quantities; market fills deduct from front.

Bounded Deduplication

Market data occasionally duplicates; deduplicate by trade ID, keep recent N:

fn is_duplicate(seen: &mut IndexSet<u64>, trade_id: u64, cap: usize) -> bool {
    if !seen.insert(trade_id) {
        return true;
    }
    if seen.len() > cap {
        seen.shift_remove_index(0); // evict oldest
    }
    false
}

Single IndexSet handles dedup + FIFO eviction; no separate VecDeque needed. shift_remove_index(0) O(n); for large capacity/high throughput, switch to HashSet + VecDeque.

Name-to-Index Mapping

Trading system loads all contracts at startup; hot path repeatedly accesses state by contract. Map names to dense indices at startup:

let mut instruments: FxIndexMap<String, InstrumentState> = FxIndexMap::default();
let (aapl, _) = instruments.insert_full("AAPL".to_string(), InstrumentState::default());

// Hot path: index access, no hash
instruments[aapl].position += 1;

Wrap index in newtype ( struct InstrumentIndex(usize)) to avoid confusion. Name→index lookup only during message parsing; rest of pipeline passes index. Requires append-only during run (no delete, sort, move, swap) else indices invalidate.

Ordered Serialization

Enable serde feature: IndexMap serializes in insertion order, deserializes preserving original order. Order parameters, strategy configs as IndexMap<String, Value> → JSON field order matches write order; logs diff cleanly, tests compare strings directly.

Caveat: serde_json 's preserve_order feature swaps its internal Map from BTreeMap to IndexMap globally (Cargo features merge). If signing code relies on serde_json::Map iteration for sorted params, a transitive dependency enabling preserve_order breaks signatures non-deterministically. Always sort explicitly before signing; don't depend on container iteration order.

Unsuitable Scenarios

Large lookup-only tables : extra memory, slower lookup → use HashMap.

Frequent reordering : LRU cache (move-to-end on access) needs O(n) move_index; use dedicated LRU implementation.

Key-sorted iteration required : IndexMap only guarantees insertion order; sort_keys doesn't auto-maintain → use BTreeMap.

Conclusion

Need stable iteration order, or iteration more frequent than lookup → IndexMap. Very large tables, lookup-only → HashMap still faster. On deletion, decide whether order matters and choose swap_remove (O(1), unordered) or shift_remove (O(n), ordered).

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

performanceRustserializationdeduplicationHashMapdata structureshash tablesbenchmarksorder bookBTreeMapIndexMapinsertion order

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion