Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Choosing a Container

Measured ratios for several containers are in Benchmarks. They come from one machine and serve as a reference.

NeedUseInstead ofAvoid when
Membership in dense integer ranges, ordered queries or range updatesPagedBitSetPagedSparseSetkeys are thinly scattered or you need a contiguous key array
Integer keys in runs or ranges; fast iteration and missesPagedSparseSet, PagedSparseMapHashSet, HashMap, BTreeMapkeys are spread uniformly over a wide range
Key-ordered iteration, range and nearest-key queries over dense rangesPagedDirectMapBTreeMapkeys are sparse inside their pages (iteration scans whole pages)
Entries as contiguous slices or arraysPagedSparseMap (key_slice, value_slice; Python views)HashMap
Priority changes or removal by keyPagedPriorityQueuepriority-queue cratepriorities never change: BinaryHeap is faster
Shared FIFO queueConcurrentQueue (Python ConcurrentQueue)
Shared indexed priority queueConcurrentPriorityQueue (Python ConcurrentPriorityQueue, ConcurrentPriorityQueueF64); relaxed pop, exact pop_exact
References that survive growthPagedVec, PagedDequeVec, VecDequerandom access dominates and addresses need not be stable
Handles that detect removal (stale ids)Hive, or IdAllocator with a paged mapslotmapraw lookup speed matters more than stable addresses
Shared insertion from many threadsconcurrent containersa Mutex around a plain containera single thread mutates: the plain types are faster

Sparse Map or Direct Map

For key 9 the sparse map's page slot points to dense position 1. The direct map's page slot holds the value 90 itself.
With the same keys and values, a sparse map iterates the dense arrays. A direct map visits slots in ascending key order for integer keys.
PagedSparseMapPagedDirectMap
Where values livedense array, parallel to the keysin the page slot
Lookuppage lookup, slot read, dense readpage lookup, slot read
Iterationdense array only, insertion order (changed by swap removal)every allocated slot, key order
clearO(1) for the indexscans allocated pages
Memory per allocated pagePAGE × 4 bytesPAGE × slot size
Range queries in Rustrange, next_occupant, prev_occupantrange, next_occupant, prev_occupant

Prefer the direct map when keys fill a few dense ranges, when you want iteration in key order, or when lookups dominate. Prefer the sparse map when keys are scattered thinly or when you need contiguous slices.

Hive or IdAllocator with a Map

Hive<T> owns the elements. A removed element’s id goes stale. An IdAllocator owns only the ids. Values live in one or more paged maps keyed by Id. Use the allocator when an entity has several components stored in separate tables, and the hive when one value per id is enough.

Directory

KeysDirectory
Below a few billion (u32)Flat (default)
Spread over 64 bitsRadix
Measured to favour a B-treeTree

See Paging Model.