Overview
paged-collections provides sparse sets, maps, a priority queue and
stable-address containers whose memory is split into fixed-size pages. The
core is a no_std Rust crate (alloc only). The Python package wraps it with
PyO3 and exchanges batches with NumPy.
Documentation
Two Uses of Paging
- Paged index. A table indexed by key is split into pages allocated on
first use. A write to an isolated key allocates only the page it touches.
With the default
Flatdirectory, the pointer table still grows up to the highest page number used. Sparse sets, sparse maps, direct maps and priority queues use a paged index. - Paged storage. Growth adds pages while existing elements stay at their addresses. The paged vector, deque and hive use paged storage.
See Paging Model for page sizes, directories and memory behaviour.
Example
A Hive stores elements at stable addresses and returns generational ids.
Those ids can index the other maps directly to create side tables:
from paged_collections import Hive, IdMap, id_generation, id_index
hive = Hive()
a = hive.insert("a")
b = hive.insert("b")
score = IdMap([a, b], [10, 20])
hive.pop(a)
c = hive.insert("c")
print("reused slot =", (id_index(c), id_generation(c)))
print("new side entry =", score.get(c))
# Writing the new generation evicts the stale entry from the side table.
score[c] = 30
print("stale hive =", hive.get(a))
print("stale side =", score.get(a))
print("side values =", score.values())
use paged_collections::direct_map::PagedDirectMap;
use paged_collections::hive::Hive;
use paged_collections::id_alloc::Id;
fn main() {
let mut hive: Hive<&str> = Hive::new();
let a = hive.insert("a");
let b = hive.insert("b");
let mut score: PagedDirectMap<Id, u32> = PagedDirectMap::new();
score.insert(a, 10);
score.insert(b, 20);
hive.remove(a);
let c = hive.insert("c");
println!("reused slot = {:?}", (c.index(), c.generation().get()));
println!("new side entry = {:?}", score.get(c));
// Writing the new generation evicts the stale entry from the side table.
score.insert(c, 30);
println!("stale hive = {:?}", hive.get(a));
println!("stale side = {:?}", score.get(a));
let values: Vec<_> = score.range(a..=b).map(|(_, &v)| v).collect();
println!("range = {values:?}");
}
Python output:
reused slot = (0, 2)
new side entry = None
stale hive = None
stale side = None
side values = [30, 20]
The Rust example queries the direct map by key range and prints
range = [30, 20] in place of the last line.
Containers
| Rust | Python | Paging | Purpose |
|---|---|---|---|
PagedSparseSet<K> | SparseSet | index | Integer set: O(1) insert, remove, contains and clear; dense iteration |
PagedSparseMap<K, V> | SparseMap, SparseMapF64, … | index | Sparse set with a dense value array |
PagedDirectMap<K, V> | DirectMap, DirectMapF64, … | index | Values stored in place; key order and range queries |
PagedPriorityQueue<K, P> | PriorityQueue, PriorityQueueF64 | index | Indexed heap with priority changes and removal by key |
ConcurrentPriorityQueue<K, P> | ConcurrentPriorityQueue, ConcurrentPriorityQueueF64 | index | Sharded max-priority queue; relaxed pop, exact pop_exact |
PagedVec<T> | PagedList, PagedListF64, … | storage | Growable vector with stable addresses |
PagedDeque<T> | PagedDeque | storage | Double-ended queue with stable addresses |
ConcurrentQueue<T> | ConcurrentQueue | storage | Shared FIFO queue; waits at page boundaries |
Hive<T> | Hive | storage | Unordered slots with generational ids |
IdAllocator | IdAllocator, IdMap | none | Generational id allocation for use as keys |
Thread-safe variants are listed under Concurrent Containers.
The full Rust API is on docs.rs; the
Python API is typed in _core.pyi.
Installation
Rust
cargo add paged-collections
Minimum supported Rust version: 1.85 (edition 2024).
| Feature | Default | Effect |
|---|---|---|
std | yes | std-only conveniences. Without it the crate is no_std and needs only alloc. |
serde | no | Serialize / Deserialize for the collections. |
concurrent | no | The concurrent module. Needs pointer-sized and 64-bit atomics on a 32- or 64-bit target; works without std (locks then spin). |
[dependencies]
paged-collections = { version = "0.2", default-features = false, features = ["concurrent"] }
Hive, IdAllocator and the concurrent module exist only on 32- and 64-bit
targets, because slot indices are u32 and must convert to usize without
loss.
Python
pip install paged-collections
Requires Python 3.10 or newer and NumPy 1.24 or newer. Wheels:
| Interpreter | Wheel tag |
|---|---|
| CPython 3.10+ with the GIL | abi3 |
| Free-threaded CPython 3.14t | version-specific |
| Free-threaded CPython 3.15t and newer | abi3t |
Free-threaded 3.13t is not supported. See Python Threads.
Page Sizes
Python classes take a page_size= keyword. The values a build accepts are
fixed at compile time, because each page size is a separate monomorphized
Rust type:
import paged_collections as pc
pc.PAGE_SIZES # (256, 512, 1024, 2048, 4096)
pc.DEFAULT_PAGE_SIZE # 1024
m = pc.SparseMap(page_size=4096)
BitSet uses the same compiled sizes, measured in 64-bit words. It defaults
to DEFAULT_BIT_PAGE_SIZE (512, or DEFAULT_PAGE_SIZE when a custom build
leaves 512 out). To build from source with other sizes, set the variables
before building:
PAGED_COLLECTIONS_PAGE_SIZES=64,1024,16384 \
PAGED_COLLECTIONS_DEFAULT_PAGE_SIZE=1024 \
pip install --no-binary paged-collections paged-collections
Each extra size adds code for every class, so the extension grows with the list.
From Source
git clone https://github.com/inspiros/paged-collections
cd paged-collections
cargo test # Rust
uv sync && uv run pytest # Python (builds the extension with maturin)
cargo build --workspace fails to link the Python crate unless the Python
development library is installed; build it through maturin (uv sync or
maturin develop). cargo check and cargo clippy work either way.
Paging Model
Paged Index
Keyed collections map each key to a slot index (the integer itself, or the index part of a generational id; see Ids and Side Tables). The slot index splits into a page number and an offset:
page = index / PAGE
offset = index % PAGE
A directory maps page numbers to pages. A page is a fixed array of PAGE
slots, allocated on the first write into it. Lookups into an unallocated page
return “absent” without allocating.
What a slot holds depends on the collection:
| Collection | Slot contents | Slot size |
|---|---|---|
| Sparse set, sparse map, priority queue | position in the dense array (Option<NonZeroU32>) | 4 bytes |
| Direct map | the value and the key’s tag (Option<(K::Tag, V)>) | size_of::<Option<(K::Tag, V)>>(); 16 bytes for u32 -> u64 |
With the default PAGE = 1024, a sparse-set page is 4 KiB and a
u32 -> u64 direct-map page is 16 KiB.
Directories
The directory is the last type parameter, for example
PagedDirectMap<usize, u32, 1024, page::Radix>.
| Marker | Structure | Page lookup | Directory memory |
|---|---|---|---|
page::Flat (default) | Vec<Option<Box<[T; PAGE]>>> | O(1), one indirection | one pointer per page up to the highest page used |
page::Radix | flat window for low page numbers, then a path-compressed 64-ary trie | O(1) in the window, else at most ceil(usize bits / 6) branches | proportional to the peak allocated page count |
page::Tree | BTreeMap<usize, Box<[T; PAGE]>> | O(log pages) | proportional to allocated pages |
- Flat suits keys below a few billion, such as
u32keys. Its directory holds at mostceil(2^32 / PAGE)pointers: 32 MiB at the default page size, plus up to as much again inVecgrowth capacity untilshrink_to_fit. - Radix suits page numbers spread over the 64-bit range, where a flat directory cannot be allocated. Its flat window covers page numbers below about 8 times the allocated page count, so dense low keys cost the same as Flat. The window does not shrink below its highest live page.
- Tree is a standard B-tree; use it when measurements favour it for your key pattern.
Python classes always use Flat; their keys are below 2**32.
Page Size
PAGE is a const generic, default 1024. Larger pages mean fewer directory
entries and fewer allocations for dense keys, and more memory per isolated
key. Smaller pages waste less memory on sparse or clustered keys.
The page-size sweep in Benchmarks shows the trade
for each key pattern. In Python, pass page_size= (see
Installation).
Memory Behaviour
- Each newly touched page costs a full page. Keys spread uniformly over a wide range allocate and zero one page per key. This is the worst case for every paged-index collection; use a hash map for it.
- Clustered keys fill pages partially. Runs of 64 keys fill about 6% of a 1024-slot page.
- Pages are not freed when they empty.
clearkeeps pages for reuse.shrink_to_fitfrees empty pages (sparse set and map: all pages, only when empty),resetfrees all pages. Removing a random 90% of keys frees almost nothing, because nearly every page stays partly occupied. - No automatic compaction. Compaction would move elements and break the address and id guarantees.
Paged Storage
PagedVec, PagedDeque and Hive keep elements in pages of PAGE elements.
A page is allocated once and never reallocated. When the container needs
more slots, it adds a page and may grow the directory of page pointers.
Vec can move its buffer when it grows. A PagedVec preserves the addresses of existing elements as it adds pages.- Pushing preserves the addresses of existing elements, including when a front push changes their logical indices in a deque. Edits such as inserting into the middle of a sequence can move elements.
- At a page boundary, a push may allocate a page and copy the directory of page pointers.
- The elements are not one contiguous slice. Slices are available per page
(
pages()in Rust,page_view()for typed Python lists).
Example
from paged_collections import DirectMap
page_size = 4096
keys = [7, 5000, 4_000_000_000]
values = DirectMap(page_size=page_size)
for key in keys:
values[key] = key + 1
print("page size =", values.page_size)
print("keys =", list(values))
print("len =", len(values))
print("allocated pages =", values.allocated_pages)
use paged_collections::direct_map::PagedDirectMap;
use paged_collections::page::Radix;
fn main() {
const PAGE: usize = 4096;
let keys = [7, 5000, 4_000_000_000usize];
let mut values: PagedDirectMap<usize, usize, PAGE, Radix> = PagedDirectMap::new();
for key in keys {
values.insert(key, key + 1);
}
println!("page size = {PAGE}");
println!("keys = {:?}", values.keys().collect::<Vec<_>>());
println!("len = {}", values.len());
println!("allocated pages = {}", values.allocated_pages());
}
Python output:
page size = 4096
keys = [7, 5000, 4000000000]
len = 3
allocated pages = 3
The Rust example prints the same lines.
Choosing a Container
Measured ratios for several containers are in Benchmarks. They come from one machine and serve as a reference.
| Need | Use | Instead of | Avoid when |
|---|---|---|---|
| Membership in dense integer ranges, ordered queries or range updates | PagedBitSet | PagedSparseSet | keys are thinly scattered or you need a contiguous key array |
| Integer keys in runs or ranges; fast iteration and misses | PagedSparseSet, PagedSparseMap | HashSet, HashMap, BTreeMap | keys are spread uniformly over a wide range |
| Key-ordered iteration, range and nearest-key queries over dense ranges | PagedDirectMap | BTreeMap | keys are sparse inside their pages (iteration scans whole pages) |
| Entries as contiguous slices or arrays | PagedSparseMap (key_slice, value_slice; Python views) | HashMap | |
| Priority changes or removal by key | PagedPriorityQueue | priority-queue crate | priorities never change: BinaryHeap is faster |
| Shared FIFO queue | ConcurrentQueue (Python ConcurrentQueue) | ||
| Shared indexed priority queue | ConcurrentPriorityQueue (Python ConcurrentPriorityQueue, ConcurrentPriorityQueueF64); relaxed pop, exact pop_exact | ||
| References that survive growth | PagedVec, PagedDeque | Vec, VecDeque | random access dominates and addresses need not be stable |
| Handles that detect removal (stale ids) | Hive, or IdAllocator with a paged map | slotmap | raw lookup speed matters more than stable addresses |
| Shared insertion from many threads | concurrent containers | a Mutex around a plain container | a single thread mutates: the plain types are faster |
Sparse Map or Direct Map
PagedSparseMap | PagedDirectMap | |
|---|---|---|
| Where values live | dense array, parallel to the keys | in the page slot |
| Lookup | page lookup, slot read, dense read | page lookup, slot read |
| Iteration | dense array only, insertion order (changed by swap removal) | every allocated slot, key order |
clear | O(1) for the index | scans allocated pages |
| Memory per allocated page | PAGE × 4 bytes | PAGE × slot size |
| Range queries in Rust | range, next_occupant, prev_occupant | range, 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
| Keys | Directory |
|---|---|
Below a few billion (u32) | Flat (default) |
| Spread over 64 bits | Radix |
| Measured to favour a B-tree | Tree |
See Paging Model.
Bit Set
PagedBitSet<K, PAGE = 512, D = Flat> (Python BitSet) stores membership
as one bit per slot in each allocated page. Pick it for integer keys that
cluster in dense ranges, especially for ordered traversal, range updates
or set algebra. A sparse set visits its dense key array
in O(len), which can be faster when the occupied pages hold few keys. It
also supports generational keys and contiguous access to the keys.
Pages and Costs
PAGE in Rust and page_size in Python count 64-bit words. The default
of 512 words uses 4 KiB per allocated page and covers 32,768 keys. Pages are
allocated as keys are inserted. Clearing the set or removing keys keeps the
pages for reuse. In Rust, shrink_to_fit() frees empty pages and reset()
frees all pages.
The Python binding uses the Flat directory and accepts the sizes in
PAGE_SIZES. Each directory slot holds one page pointer up to the
highest allocated page. At the default size, the full Python key domain
needs at most 131,072 directory slots (1 MiB of pointers on a 64-bit
platform). Rust can use a different directory
for keys spread over a wider domain.
| Operation | Cost with Flat |
|---|---|
| Membership, insert, remove | O(1) per key, plus allocation on first touch |
| Length | O(1) |
| Iteration, nearest-key queries | Scan directory slots and words in the visited span, then visit set bits |
| Range add | Visit words in the range and allocate newly touched pages |
| Range discard, count | Scan directory slots and words in allocated pages that overlap the range |
| Clear | Zero the words in all allocated pages |
| Same-size set algebra | Scan relevant pages word by word |
Rust
Integer key types implement DirectKey<Tag = ()>. Ranges take Rust
RangeBounds<K> and refer to the keys’ slot indices. Use explicit upper
bounds for narrow integer key types when adding a range. Bit sets with
the same PAGE support algebra across directory layouts.
#![allow(unused)]
fn main() {
use paged_collections::bit_set::PagedBitSet;
let mut bits: PagedBitSet<u32> = PagedBitSet::new();
assert_eq!(bits.insert_range(62..67), 5);
assert_eq!(bits.remove_range(64..66), 2);
assert_eq!(bits.range(63..).collect::<Vec<_>>(), [63, 66]);
assert_eq!(bits.next_occupant(64), Some(66));
assert_eq!(bits.pop_first(), Some(62));
}
Python
from paged_collections import BitSet
bits = BitSet([62, 65])
print(bits.add_range(63, 67))
print(list(bits.range(63, 67)))
print(bits.next_occupant(64))
print(bits.to_mask(61, 68).tolist())
print(BitSet.from_mask([True, False, True], offset=62).to_numpy().tolist())
3
[63, 64, 65, 66]
64
[False, True, True, True, True, True, False]
[62, 64]
- Keys are integers in
0 <= key < 2**32. Membership and discard treat invalid keys as absent.addraises for invalid keys andremoveraisesKeyErrorfor absent keys. BitSet(keys=None, *, page_size=DEFAULT_BIT_PAGE_SIZE)accepts an initial one-dimensional integer array or sequence.toggle(key)flips membership and returns whether the key is now present. It validates keys the same way asadd.first()andlast()return the smallest and largest keys.pop_first()andpop_last()remove and return the respective keys.pop()is the same aspop_first(). These methods raiseKeyErroron an empty set.next_occupant(index)andprev_occupant(index)return the nearest key at or beyond the given key in the respective direction, orNoneif there is no match. The index must be a valid key.add_rangeanddiscard_rangereturn the number of keys changed.count_rangecounts keys andrangeiterates over them. Both endpoints of[start, stop)must be integers in0 <= endpoint <= 2**32. Withstart >= stopthe interval is empty.- Iteration is ascending, or descending with
reversed(bits). Iterators raiseRuntimeErrorif membership changes during iteration. union,intersection,difference,symmetric_difference, their in-place methods (updatefor union) and the predicates accept iterable operands. Operators| & - ^, their in-place forms and comparisons takeBitSetoperands. Two bit sets with the same page size use word-wise algebra. With different sizes, algebra visits keys individually. New algebra results are baseBitSetinstances using the receiver’s page size. Pickling and copying preserve the page size.add_manyanddiscard_manyreturn the number of keys changed.contains_manyreturns a boolean NumPy array.to_numpy()returns a new ascendinguint32array.from_mask(mask, offset=0, *, page_size=DEFAULT_BIT_PAGE_SIZE)reads a one-dimensional boolean array or sequence. A true value at positionisetsoffset + i. The whole mask must fit in the key domain. The page size counts 64-bit words, as in the constructor.to_mask(start, stop)returns a new boolean array with one element per key in the interval, using O(max(0, stop − start)) memory.
API PagedBitSet.
Sparse Set
PagedSparseSet<K, PAGE = 1024, D = Flat> (Python: SparseSet) stores keys in
a contiguous dense array and finds them through a paged sparse index from
slot index to dense position.
Example
from paged_collections import SparseSet
keys = SparseSet([3, 7, 11])
keys.add(19)
print("inserted =", list(keys))
keys.remove(7)
print("contains 7 =", 7 in keys)
print("dense =", list(keys))
other = SparseSet([11, 23])
print("union =", sorted(keys | other))
print("intersection =", sorted(keys & other))
print("difference =", sorted(keys - other))
keys.clear()
print("cleared len =", len(keys))
use paged_collections::sparse_set::PagedSparseSet;
fn main() {
let mut keys: PagedSparseSet<usize> = PagedSparseSet::new();
keys.extend([3, 7, 11]);
keys.insert(19);
println!("inserted = {:?}", keys.as_slice());
keys.remove(7);
println!("contains 7 = {}", keys.contains(7));
println!("dense = {:?}", keys.as_slice());
keys.clear();
println!("cleared len = {}", keys.len());
}
Python output:
inserted = [3, 7, 11, 19]
contains 7 = False
dense = [3, 19, 11]
union = [3, 11, 19, 23]
intersection = [11]
difference = [3, 19]
cleared len = 0
The Rust example prints the same lines without the set algebra.
Complexity
| Operation | Cost |
|---|---|
| insert, remove, contains, get, take | O(1) with Flat; O(depth) with Radix; O(log pages) with Tree |
| clear | O(1): pages are kept, stale slots are ignored |
iteration, as_slice | dense array only, O(len) |
| sort | O(n log n) comparisons, then one index write per key |
Lookups follow Briggs and Torczon. A lookup accepts a slot only if it points
inside the dense array to a key with the same slot index. This check lets
clear leave the index pages untouched.
Order
Iteration follows the dense array in insertion order until a removal. remove
swaps the last key into the removed position (O(1)), changing the order.
sort and its variants reorder the dense array. Sorted order then lasts until
the next removal or insertion out of order.
Generational Keys
The set holds at most one key per slot index. With generational keys,
insert refuses a key whose slot is held by another generation and returns
false; replace evicts the other generation; occupant(index) returns the
key holding a slot. get(key) borrows the stored key and take(key)
removes and returns it. Both require an exact generation match.
See Ids and Side Tables.
Rust and Python
| Rust | Python | Notes |
|---|---|---|
insert(k) -> bool | add(k), add_many(keys) -> int | |
remove(k) -> bool | discard(k), remove(k) (raises KeyError), discard_many(keys) | swap removal |
contains(k) | k in s, contains_many(keys) -> ndarray[bool] | |
get(k) | borrows the stored key | |
take(k) | returns the stored key by swap removal | |
as_slice() | to_array() (copy), view() (zero-copy, read-only) | |
iter() | iter(s) | dense order |
first(), last() | first(), last() | smallest and largest keys |
pop_first(), pop_last() | pop_first(), pop_last() | remove and return the smallest and largest keys, respectively |
next_occupant, prev_occupant | next_occupant(index), prev_occupant(index) | nearest key at or after, or at or before, index |
sort* | sort() | |
position(k) | dense position | |
clear() / reset() | clear() | reset frees pages |
allocated_pages() | allocated_pages | |
union, intersection, difference, symmetric_difference, the *_update forms, | & - ^ and in-place operators, issubset, issuperset, isdisjoint, < <= > >= | Python set protocol |
Python keys are integers in 0 <= key < 2**32. Batch lookups
(contains_many, discard_many) treat out-of-range integers as absent;
add and add_many raise for them.
Ordered queries use the sparse index, and next_occupant and prev_occupant
require a valid key and return None when no key matches. first(), last(),
pop_first() and pop_last() raise KeyError on an empty set. Ordered pops
use swap removal and raise BufferError while a view() is alive.
Set Algebra
- Operators take
SparseSetoperands; methods accept any iterable of keys. - Results use the receiver’s page size, keep the receiver’s surviving keys in order, then append new keys in operand iteration order.
difference_updateand-=use swap removal; other in-place operations keep the receiver’s order.- In-place operations raise
BufferErrorwhile aview()is alive.
API: PagedSparseSet.
Sparse Map
PagedSparseMap<K, V, PAGE = 1024, D = Flat> is a sparse set
of keys plus a dense value array kept parallel to the dense keys. The value at
position i belongs to the key at position i. Keys and values can be
iterated or borrowed as slices without touching the index.
See where sparse and direct maps store their values.
Python: SparseMap holds arbitrary objects. SparseMapF64, SparseMapF32,
SparseMapI64, SparseMapI32, SparseMapU64, SparseMapU32 and
SparseMapBool store values unboxed; sparse_map(dtype) returns an instance
of the class for a NumPy dtype.
Example
from paged_collections import SparseMap, sparse_map
values = sparse_map("float64")
values[7] = 1.5
values[2] = 2.5
values[9] = 3.5
print("get 7 =", values.get(7))
print("removed =", values.pop(2))
print("keys =", list(values))
print("values =", values.values().tolist())
objects = SparseMap()
objects[7] = (4, 5)
print("object =", objects[7])
use paged_collections::sparse_map::PagedSparseMap;
fn main() {
let mut values: PagedSparseMap<usize, f64> = PagedSparseMap::new();
values.insert(7, 1.5);
values.insert(2, 2.5);
values.insert(9, 3.5);
println!("get 7 = {}", values.get(7).unwrap());
println!("removed = {}", values.remove(2).unwrap());
println!("keys = {:?}", values.keys().collect::<Vec<_>>());
println!("values = {:?}", values.values().collect::<Vec<_>>());
let mut objects: PagedSparseMap<usize, (i32, i32)> = PagedSparseMap::new();
objects.insert(7, (4, 5));
println!("object = {:?}", objects.get(7).unwrap());
}
Python output:
get 7 = 1.5
removed = 2.5
keys = [7, 9]
values = [1.5, 3.5]
object = (4, 5)
The Rust example prints the same lines.
Complexity
| Operation | Cost |
|---|---|
| get, remove | O(1) with Flat (see directories) |
| insert | as get, amortized over dense-array growth; the first key in a page allocates the page |
| clear | O(1) for the index, plus dropping the values |
iteration, key_slice, value_slice | dense arrays only |
| sort | O(n log n) comparisons, O(n) swaps, one index write per entry |
binary_search_key, binary_search_by, partition_point | O(log n) on entries kept sorted by the caller |
Removal swaps the last entry into the removed position, as in the set.
Generational Keys
With plain integer keys the map behaves like HashMap. With generational
keys the methods differ when the slot is held by a different key:
| Method | Slot held by another generation |
|---|---|
insert, get_or_insert_with | evicts it |
entry | returns Vacant. Inserting through it evicts the other generation in place |
replace | evicts it and returns the evicted entry |
try_insert | refuses |
insert evicts so that get(key) returns the new value afterwards, as with
HashMap.
In Rust, entry(key) gives mutable access to an exact key or lets you insert
it after a single slot lookup. For example, use
*counts.entry(key).or_default() += 1 to update a counter.
Rust and Python
| Rust | Python |
|---|---|
insert(k, v) | m[k] = v, set_many(keys, values), update(mapping) |
get(k), get_mut(k) | m[k], get(k, default), get_many(keys, default) |
get_or_insert_with | setdefault(k, default) |
entry(k) | |
remove(k) | del m[k], pop(k[, default]), popitem(), discard_many(keys) |
first_key_value(), last_key_value() | first_item(), last_item() |
pop_first(), pop_last() | pop_first(), pop_last() |
next_occupant, prev_occupant | next_occupant(index), prev_occupant(index) |
range(a..b) | items_range(a, b), keys_range(a, b), values_range(a, b) |
contains_key(k) | k in m, contains_many(keys) |
key_slice() | keys() (copy), keys_view() (zero-copy, read-only) |
value_slice(), value_slice_mut() | typed maps: values() (copy), values_view() (zero-copy; writeable except for SparseMapBool); SparseMap.values() returns a list |
sort_keys, sort_by* | sort_keys() |
allocated_pages() | allocated_pages |
Python SparseMap, IdMap and their typed variants accept parallel keys and
values, one mapping, or one iterable of (key, value) pairs. They validate
all input before writing and keep the last value for duplicate keys.
Ordered queries follow the sparse index. first_item() and last_item()
return the (key, value) pairs with the smallest and largest slot indices.
pop_first() and pop_last() remove and return those pairs by swap removal.
All four raise KeyError on an empty map, and ordered pops raise BufferError
while a NumPy view is alive.
next_occupant(index) and prev_occupant(index) return the nearest pair at or
after, or at or before, the given slot index. They return None when no entry
matches. Both accept integers outside the slot domain. A negative index is
before the first slot, and an index of 2**32 or higher is past the last slot.
For IdMap and its typed variants, pass a slot index and receive a packed ID
as the key in the returned pair.
items_range(start=None, stop=None), keys_range and values_range return
copies in ascending slot order for the half-open interval [start, stop).
None leaves a bound open and integer bounds are clamped to the slot domain.
For IdMap, the bounds are slot indices and the returned keys are packed IDs.
Batch methods are described in NumPy Interop.
API: PagedSparseMap.
Direct Map
PagedDirectMap<K, V, PAGE = 1024, D = Flat> stores each entry in the slot
its key names, in pages allocated on first use. There is no dense array: a
lookup is one page lookup and one slot read, entries never move, and
iteration visits entries in ascending slot-index order (key order for
integers).
See where sparse and direct maps store their values.
Python: DirectMap (objects) and DirectMapF64, DirectMapF32,
DirectMapI64, DirectMapI32, DirectMapU64, DirectMapU32,
DirectMapBool; direct_map(dtype) creates an instance of the class for a dtype.
Example
from paged_collections import DirectMap
values = DirectMap([20, 3, 10], [200, 30, 100])
print("get 3 =", values.get(3))
print("default =", values.setdefault(7, 70))
print("existing =", values.setdefault(7, 999))
print("ordered =", values.items())
print("range =", values.items_range(3, 20))
print("removed =", values.pop(10))
print("keys =", list(values))
use paged_collections::direct_map::PagedDirectMap;
fn main() {
let mut values: PagedDirectMap<usize, i32> = PagedDirectMap::new();
for (key, value) in [(20, 200), (3, 30), (10, 100)] {
values.insert(key, value);
}
println!("get 3 = {}", values.get(3).unwrap());
println!("default = {}", values.entry(7).or_insert(70));
println!("existing = {}", values.entry(7).or_insert(999));
println!("ordered = {:?}", values.iter().collect::<Vec<_>>());
println!("range = {:?}", values.range(3..20).collect::<Vec<_>>());
println!("removed = {}", values.remove(10).unwrap());
println!("keys = {:?}", values.keys().collect::<Vec<_>>());
}
Python output:
get 3 = 30
default = 70
existing = 70
ordered = [(3, 30), (7, 70), (10, 100), (20, 200)]
range = [(3, 30), (7, 70), (10, 100)]
removed = 100
keys = [3, 7, 20]
The Rust example prints the same lines, using the entry API in place of setdefault.
Complexity
| Operation | Cost |
|---|---|
| get, insert, remove | O(1) with Flat; the first key in a page allocates the page |
| iteration, clear, retain | O(allocated pages × PAGE), plus with Flat O(directory length) to skip unallocated pages |
range, next_occupant, prev_occupant, first_key_value, last_key_value, pop_first, pop_last | a seek to the first page (O(1) with Flat, O(depth) with Radix and Tree), then a scan of the allocated slots up to the entry; with Flat, unallocated directory entries in between are also skipped one by one |
| len | O(1) |
Iteration and clear scan every allocated slot, occupied or not, and every
allocated slot takes the space of an entry. Keys that fill their pages
sparsely make both expensive; see Choosing a Container.
What a Slot Stores
A slot holds the value and the key’s DirectKey::Tag, the part of the key its
slot index does not give. Integer keys have the tag (), so a slot of a
u32 -> u64 map is 16 bytes and a slot of a u32 -> Box<T> map is 8 bytes
(niche optimization). Iterators rebuild each key from slot index and tag and
yield keys by value: (K, &V).
Ordered Queries
Entries are ordered by slot index, so the map answers ordered-map queries without a tree:
range(a..b),range_mut: entries between two keys.first_key_value,last_key_value,pop_first,pop_last: the ends.next_occupant(i),prev_occupant(i): the nearest entry at or after, or at or before, slot indexi.
A generational key bounds a range by its index only: range(id..=id) yields
whichever generation holds the slot.
Entry API
entry(k) returns Occupied only when the slot holds k itself. A vacant
entry’s insert evicts another generation held in the slot. The usual
combinators exist: or_insert, or_insert_with, or_insert_with_key,
or_default, and_modify, insert_entry.
Generational Keys
As in the sparse map: insert and
get_or_insert_with evict another generation, replace evicts and returns
it, try_insert refuses. Keys must implement DirectKey (the Key slot
index plus the tag); u8, u16, u32, u64, usize and Id implement it.
Memory
Pages are not freed when they empty. shrink_to_fit frees every page without
entries and shrinks the directory; reset frees all pages.
Rust and Python
| Rust | Python |
|---|---|
insert(k, v) | m[k] = v, set_many(keys, values), update(mapping) |
get(k) | m[k], get(k, default), get_many(keys, default) |
get_or_insert_with, entry | setdefault(k, default) |
remove(k) | del m[k], pop(k[, default]), popitem(), discard_many(keys) |
keys(), values(), iter() | keys() (uint32 array), values(), items() |
range(a..b) | keys_range(a, b), values_range(a, b), items_range(a, b) (stop exclusive) |
first_key_value, last_key_value | first_item(), last_item() |
pop_first, pop_last | pop_first(), pop_last() |
next_occupant, prev_occupant | next_occupant(i), prev_occupant(i) |
shrink_to_fit, reset | shrink_to_fit() |
Python DirectMap and its typed variants accept parallel keys and values,
one mapping, or one iterable of (key, value) pairs. They validate all input
before writing and keep the last value for duplicate keys.
Python direct maps have no zero-copy views: values are in pages, not in one array.
API: PagedDirectMap.
Priority Queue
PagedPriorityQueue<K, P, PAGE = 1024, D = Flat> is an indexed max-heap: keys
map to priorities, the greatest priority comes out first, and a key’s priority
can be changed or the key removed in O(log n). Use core::cmp::Reverse for a
min-queue. Keys and priorities live in parallel contiguous arrays in heap
order (a four-way heap); a paged index finds a key’s heap position.
Python: PriorityQueue (int64 priorities) and PriorityQueueF64 (float64);
min=True makes either a min-queue. Pushing a present key changes its
priority.
pop takes the root of the heap. Updating key 9 starts at position 2, and the entry moves if its new priority requires it.Example
from paged_collections import PriorityQueue, PriorityQueueF64
queue = PriorityQueue()
for key, priority in [(7, 10), (2, 30), (9, 20), (4, 15)]:
queue.push(key, priority)
# Pushing an existing key changes its priority and returns the old priority.
print("old priority =", queue.push(7, 40))
print("removed =", queue.remove(9))
print("pop order =", [queue.pop() for _ in range(len(queue))])
floats = PriorityQueueF64(min=True)
floats.push(7, 1.5)
floats.push(2, 0.5)
floats.push(9, 2.5)
floats.push(7, 0.25)
floats.remove(9)
print("float min order =", [floats.pop() for _ in range(len(floats))])
use paged_collections::priority_queue::PagedPriorityQueue;
fn main() {
let mut queue: PagedPriorityQueue<usize, i32> = PagedPriorityQueue::new();
for (key, priority) in [(7, 10), (2, 30), (9, 20), (4, 15)] {
queue.push(key, priority);
}
println!("old priority = {}", queue.change_priority(&7, 40).unwrap());
println!("removed = {}", queue.remove(&9).unwrap().1);
let mut order = Vec::new();
while let Some(item) = queue.pop() {
order.push(item);
}
println!("pop order = {order:?}");
}
Python output:
old priority = 10
removed = 20
pop order = [(7, 40), (2, 30), (4, 15)]
float min order = [(7, 0.25), (2, 0.5)]
The Rust example prints the first three lines.
Complexity
| Operation | Cost |
|---|---|
| push, pop, change_priority, remove | O(log n) comparisons |
| peek, priority, contains_key | O(1) |
into_sorted_vec | O(n log n) |
Equal priorities come out in unspecified order.
In Rust, try_reserve(additional) reserves room in both dense arrays.
If capacity overflows or allocation fails, the queue keeps its entries,
array addresses and capacity.
Generational Keys
A slot holds one key. push evicts another generation of the key’s slot;
try_push refuses. Lookups check the whole key.
Panic Safety
If a priority comparison or a change_priority_with closure panics, every
remaining entry stays findable and paired with its priority, but heap order
may be broken: later pop and sorted results are unspecified. The same
applies when a stored priority’s ordering changes through interior
mutability. Neither causes undefined behaviour.
Rust and Python
| Rust | Python |
|---|---|
push(k, p) -> Option<P> | push(k, p), q[k] = p |
try_push | |
push_increase, push_decrease | push_increase(k, p), push_decrease(k, p) |
pop(), peek() | pop(), peek() (raise IndexError when empty) |
change_priority(&k, p), change_priority_with | push(k, p), q[k] = p |
priority(&k) | q[k], get(k, default) |
remove(&k) | remove(k), del q[k] |
into_sorted_vec, into_sorted_iter | sorted() |
keys, priorities, key_slice, priority_slice | keys(), items() |
reserve, try_reserve |
Python push_increase and push_decrease insert an absent key or update its
priority only when the new numeric value is strictly greater or strictly
smaller, respectively. Both return whether the queue changed. With
min=True, pop() selects the lowest priority and these methods keep their
numeric meanings.
API: PagedPriorityQueue.
Paged Vector
PagedVec<T, PAGE = 1024> is a growable vector stored in fixed-size pages. A
page is allocated once and never reallocated, so pushing never moves or copies
existing elements.
Python: PagedList (objects) and PagedListF64, PagedListF32,
PagedListI64, PagedListI32, PagedListU64, PagedListU32,
PagedListBool. These classes implement the list protocol.
paged_list(dtype) creates an instance of the class for a dtype.
Example
from paged_collections import PagedList
values = PagedList([1, 2, 3])
values.extend(range(4, 10_001))
print("len =", len(values))
print("first =", values[0])
print("last =", values[-1])
print("popped =", values.pop())
values.insert(1, 99)
print("removed =", values.pop(1))
print("prefix =", list(values[:3]))
use paged_collections::paged_vec::PagedVec;
fn main() {
let mut values: PagedVec<i32> = PagedVec::new();
values.extend([1, 2, 3]);
let first: *const i32 = &values[0];
for value in 4..=10_000 {
values.push(value);
}
println!("len = {}", values.len());
println!("first = {}", values[0]);
println!("last = {}", values[values.len() - 1]);
println!("same address = {}", std::ptr::eq(first, &values[0]));
println!("popped = {}", values.pop().unwrap());
values.insert(1, 99);
println!("removed = {}", values.remove(1));
println!("prefix = {:?}", values.iter().take(3).collect::<Vec<_>>());
}
Python output:
len = 10000
first = 1
last = 10000
popped = 10000
removed = 99
prefix = [1, 2, 3]
The Rust example also prints same address = true. Element 0 kept its
address through 10,000 pushes.
Address Stability
- An element keeps its address while it stays at the same index, through any
number of
push,extendandreservecalls. - Operations that change which element sits at an index (
insert,remove,swap,swap_remove,retain,dedup,drain,extract_if) move elements, as in aVec. split_offat a page boundary transfers whole pages without moving their elements.
Complexity
| Operation | Cost |
|---|---|
get, indexing, pop | O(1) |
push | amortized O(1): one page allocation every PAGE pushes, rare directory growth |
insert, remove | O(len − index) |
truncate, clear | O(removed) drops; pages are kept |
extract_if | O(visited), plus shifting the tail after a removal. No allocation. |
split_off | O(transferred pages) at a page boundary, else O(len − at) |
binary_search, partition_point | O(log n), no allocation |
sort and variants | the slice sort, plus moving all elements out to a temporary buffer and back |
The worst-case push costs one page allocation plus a copy of the page
directory, which is PAGE times shorter than the elements. A Vec instead
copies all elements on growth.
In Rust, extract_if(range, filter) visits that range in order and yields
the elements for which the filter returns true. The filter can mutate each
element. Dropping the iterator early keeps the unvisited elements in order.
If the filter panics, the current element is kept with its mutations.
No Contiguous Slice
There is no as_slice or Deref<Target = [T]>. Use pages() and
pages_mut() for per-page slices, or with_contiguous_mut to run a slice
algorithm on all elements through a temporary buffer. Typed Python lists
expose pages as NumPy views (page_view(i), page_views()) and copy
everything with to_numpy().
Rust and Python
| Rust | Python |
|---|---|
push, extend | append, extend, += |
pop, insert, remove | pop([i]), insert(i, v), del l[i]; remove(value) searches by value |
indexing, range | l[i], l[a:b] (slices copy) |
extract_if(range, filter) | |
sort* | sort(key=, reverse=) (typed lists: reverse= only) |
pages() | typed: page_view(i), page_views() |
typed: get_many(indices), set_many(indices, values), to_numpy(), np.asarray(l) | |
reserve, shrink_to_fit, capacity | same names; capacity, allocated_pages are properties |
API: PagedVec.
Deque
PagedDeque<T, PAGE = 1024> is a double-ended queue stored in fixed-size
pages. An element keeps its address for as long as it stays in the deque,
through pushes and pops at either end, reserve and shrink_to_fit. Spare
pages are kept at the back and reused at either end.
Python: PagedDeque follows collections.deque (CPython 3.12 semantics),
including maxlen, rotate and the comparison operators.
Example
from paged_collections import PagedDeque
values = PagedDeque([1, 2, 3])
values.appendleft(0)
values.append(4)
print("values =", list(values))
print("index 2 =", values[2])
print("front =", values.popleft())
print("back =", values.pop())
print("remaining =", list(values))
values.rotate(1)
print("rotated =", list(values))
use paged_collections::paged_deque::PagedDeque;
fn main() {
let mut values: PagedDeque<i32> = PagedDeque::new();
values.extend([1, 2, 3]);
values.push_front(0);
values.push_back(4);
println!("values = {:?}", values.iter().collect::<Vec<_>>());
println!("index 2 = {}", values[2]);
println!("front = {}", values.pop_front().unwrap());
println!("back = {}", values.pop_back().unwrap());
println!("remaining = {:?}", values.iter().collect::<Vec<_>>());
}
Python output:
values = [0, 1, 2, 3, 4]
index 2 = 2
front = 0
back = 4
remaining = [1, 2, 3]
rotated = [3, 1, 2]
The Rust example prints the same lines without the rotation.
Complexity
| Operation | Cost |
|---|---|
| pops, access, indexing, swapping | O(1) |
| pushes | amortized O(1), occasional page allocation and directory growth |
insert, remove | O(min(index, len − index)) moves |
truncate, clear | O(removed) drops; pages are kept |
binary_search, partition_point | O(log len) |
reserve, shrink_to_fit | O(allocated or freed pages) |
Front operations change indices without moving the remaining elements. Insertion, removal, swapping and retention can move elements.
Elements are not contiguous. pages() returns the initialized part of each
used page, and the first and last slices can be partial.
Rust and Python
| Rust | Python |
|---|---|
push_back, push_front | append, appendleft |
pop_back, pop_front | pop, popleft |
extend | extend, extendleft |
front, back, indexing | d[0], d[-1], d[i] |
insert, remove | insert(i, v), del d[i]; remove(value) searches by value |
rotate(n), reverse(), count, index, maxlen | |
reserve, shrink_to_fit | same names |
API: PagedDeque.
Hive
Hive<T, PAGE = 1024> is an unordered container with stable addresses,
reusable slots and generational ids. Inserting returns an Id: a u32 slot
index plus a generation. Removing an element frees its slot; the next element
there gets the next generation, so a stale id of a removed element never
matches a live one. Comparable in purpose to C++26 std::hive.
Python: Hive; ids are integers packed as generation << 32 | index.
Example
from paged_collections import Hive, id_generation, id_index
hive = Hive()
a = hive.insert(30)
b = hive.insert(10)
print("removed =", hive.pop(a))
c = hive.insert(20)
print("reused slot =", (id_index(c), id_generation(c)))
print("stale =", hive.get(a))
ordered = hive.sorted_ids()
print("sorted indices =", [id_index(key) for key in ordered])
print("sorted values =", [hive[key] for key in ordered])
print("slots before sort =", hive.values())
# Sorting moves values between slots; ids continue to name slots.
hive.sort()
print("slots after sort =", hive.values())
print("reused id now names =", hive[c])
use paged_collections::hive::Hive;
fn main() {
let mut hive: Hive<i32> = Hive::new();
let a = hive.insert(30);
let b = hive.insert(10);
println!("removed = {}", hive.remove(a).unwrap());
let c = hive.insert(20);
println!("reused slot = {:?}", (c.index(), c.generation().get()));
println!("stale = {:?}", hive.get(a));
println!("id_of index = {}", hive.id_of(&hive[b]).unwrap().index());
let ordered = hive.sorted_ids();
let indices: Vec<_> = ordered.iter().map(|id| id.index()).collect();
println!("sorted indices = {indices:?}");
let sorted_values: Vec<_> = ordered.iter().map(|&id| hive[id]).collect();
println!("sorted values = {sorted_values:?}");
println!(
"slots before sort = {:?}",
hive.values().collect::<Vec<_>>()
);
// Sorting moves values between slots; ids continue to name slots.
hive.sort();
println!("slots after sort = {:?}", hive.values().collect::<Vec<_>>());
println!("reused id now names = {}", hive[c]);
}
Python output:
removed = 30
reused slot = (0, 2)
stale = None
sorted indices = [1, 0]
sorted values = [10, 20]
slots before sort = [20, 10]
slots after sort = [10, 20]
reused id now names = 10
The Rust example also prints id_of index = 1, the id recovered from the address of hive[b].
Guarantees
- Stable addresses. An element does not move while it is in the hive:
inserts, removals of other elements,
reserveandshrink_to_fitleave it in place. Onlysortand its variants move elements. - Slot reuse. Inserts fill one page with room at a time; within a page the last freed slot is reused first. A page with room is used before a new page is allocated, so memory follows the peak element count, not the number of inserts.
- Iteration is in slot order (page by page), not insertion order.
- Memory return.
shrink_to_fitfrees every empty page except pages holding a retired slot, scanning the slots of each empty page to check. A freed page keeps a record of its highest generation, so earlier ids stay dead when the page is reused.
Finding and Sorting
id_of(&element)returns the id of an element from its address, in O(pages).sorted_ids()(and_by,_by_key) returns live ids in element order and moves nothing.sort()(and_by,_by_key,_by_cached_key,sort_unstable*) reorders elements across the occupied slots, so iteration yields them sorted. Ids name slots: aftersort, an id names whatever element moved into its slot.
Complexity
| Operation | Cost |
|---|---|
insert, remove | amortized O(1) |
get, contains, occupant | O(1) |
| iteration | O(len) on full pages; skips empty pages, scans free slots in partial pages |
retain, clear, drain, extract_if | O(pages + len) plus the scan |
reserve, shrink_to_fit | O(pages) |
id_of | O(pages) |
Limits and Stale Ids
Slot indices are below MAX_INDICES (u32::MAX). Each slot issues at most
MAX_GENERATION (231) ids; after that the slot is retired and
never reused, so generations never wrap. A page with a retired slot is never
freed. is_exhausted reports when no slot can be issued.
The stale-id guarantee holds within one history of one hive. Ids carry no hive identity: another hive or a clone accepts them, and restoring an older state (an older clone, an older serialized snapshot, an older pickle) revives ids removed since.
Side Tables
Id implements Key and DirectKey, so PagedSparseMap<Id, V> and
PagedDirectMap<Id, V> hold extra data per element. In Python use IdMap.
See how side tables handle recycled ids.
Rust and Python
| Rust | Python |
|---|---|
insert(v) -> Id | insert(v) -> int, insert_many(values) -> ndarray[uint64] |
get(id), get_mut(id), indexing | h[id], get(id, default), get_many(ids) |
remove(id) | pop(id[, default]), del h[id], discard(id), discard_many(ids) |
contains(id) | id in h, contains_many(ids) |
ids(), values(), iter() | ids() (also keys()), values(), items(), iter(h) (ids) |
id_of(&v) | |
sorted_ids* | sorted_ids(key=, reverse=) |
sort* | sort(key=, reverse=) |
retain, shrink_to_fit, reserve | same names |
h.keys() and h.ids() each return a new uint64 array of live ids in slot
order.
API: Hive.
Ids and Side Tables
Keys and Slots
Every keyed collection stores at most one key per slot, and Key::index
names the slot. For integers the slot is the integer. For generational ids
(an index plus a generation counter) the slot is the index part, so all
generations of an id share one slot. A lookup with a generational id matches
only the generation stored in that collection.
What happens when an insert meets a slot held by another generation is
documented per method: insert evicts, replace evicts and returns,
try_insert refuses (see Sparse Map).
IdAllocator
IdAllocator hands out Ids and recycles freed ones without storing values.
Freed indices are reused last freed first, with the next generation.
index_bound() is at most the peak number of live ids plus the retired
indices, which keeps the paged indices of the maps compact.
| Operation | Cost |
|---|---|
alloc, free | amortized O(1) |
is_alive, occupant | O(1) |
iter, retain, clear | O(index_bound) |
Each index issues at most MAX_GENERATION (231) ids, then retires.
The stale-id guarantee has the same scope as for the hive:
one allocation history.
Side Tables
Use the same id as a key in separate maps when each entity has several associated values. The allocator and each map manage their own entries.
Example
from paged_collections import IdAllocator, IdMap, id_generation, id_index
ids = IdAllocator()
a, b = ids.alloc(), ids.alloc()
scores = IdMap([a, b], [10, 20])
print("freed =", ids.free(a))
c = ids.alloc()
print("reused slot =", (id_index(c), id_generation(c)))
# The side table is independent of the allocator; replace its old generation.
scores[c] = 30
print("stale alive =", ids.is_alive(a))
print("stale side =", scores.get(a))
print("scores =", scores.values())
print("live ids =", len(ids))
use paged_collections::id_alloc::{Id, IdAllocator};
use paged_collections::sparse_map::PagedSparseMap;
fn main() {
let mut ids = IdAllocator::new();
let (a, b) = (ids.alloc(), ids.alloc());
let mut scores: PagedSparseMap<Id, i32> = PagedSparseMap::new();
scores.insert(a, 10);
scores.insert(b, 20);
println!("freed = {}", ids.free(a));
let c = ids.alloc();
println!("reused slot = {:?}", (c.index(), c.generation().get()));
// The side table is independent of the allocator: writing the new generation evicts the stale entry.
scores.insert(c, 30);
println!("stale alive = {}", ids.is_alive(a));
println!("stale side = {:?}", scores.get(a));
println!("scores = {:?}", scores.values().collect::<Vec<_>>());
println!("live ids = {}", ids.len());
}
Python output:
freed = True
reused slot = (0, 2)
stale alive = False
stale side = None
scores = [30, 20]
live ids = 2
The Rust example prints the same lines.
Custom Id Types
Implement Key (and DirectKey for direct maps) for your own id:
#![allow(unused)]
fn main() {
use paged_collections::key::Key;
/// Low 24 bits: index; high 8 bits: generation.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
struct Entity(u32);
impl Key for Entity {
fn index(self) -> usize {
(self.0 & 0x00ff_ffff) as usize
}
}
}
DirectKey adds type Tag (the bits the index does not give, here the
generation), tag(self) and from_parts(index, tag).
Python Ids
Python ids are integers generation << 32 | index.
| Function | Result |
|---|---|
id_index(id), id_generation(id) | the parts |
make_id(index, generation) | a packed id (generations 1 to 2**32 − 1) |
id_indices(ids) | vectorized id_index, uint32 array |
IdMap and its typed variants (IdMapF64, …, id_map(dtype)) are sparse
maps keyed by these ids. They accept ids from IdAllocator and Hive.
Their ordered queries use slot indices and
return packed ids as keys.
| Rust | Python |
|---|---|
IdAllocator::alloc | alloc(), alloc_many(n) |
free | free(id), free_many(ids) |
is_alive | is_alive(id), id in a, is_alive_many(ids) |
iter | iter(a), ids() |
index_bound, free_len, retired_len | properties of the same names |
API: IdAllocator,
Key.
Concurrent Containers
Rust feature concurrent (see Installation). The
module uses core atomics and alloc; it does not need std.
Model: Grow Shared, Shrink Exclusive
Shared access (&self) may install pages and recycle slots. Allocated pages
and directory chunks stay at stable addresses until exclusive access (&mut self) or destruction, so memory reclamation needs no epochs or hazard
pointers. Removal of pages, conversion to plain types and shrink_to_fit
need &mut self.
Example
use paged_collections::concurrent::{ConcurrentAppendHive, ConcurrentSparseSet};
// ANCHOR: queue
fn fifo_example() {
use paged_collections::concurrent::ConcurrentQueue;
let queue = ConcurrentQueue::<_, 2>::new();
queue.push("first");
queue.push("second");
assert_eq!(queue.pop(), Some("first"));
assert_eq!(queue.pop(), Some("second"));
}
// ANCHOR_END: queue
// ANCHOR: priority_queue
fn priority_example() {
use paged_collections::concurrent::ConcurrentPriorityQueue;
let queue = ConcurrentPriorityQueue::<u32, i32, 4>::with_shards(3);
queue.push(1, 10);
queue.push(5, 20);
assert_eq!(queue.change_priority(&1, 30), Some(10));
assert_eq!(queue.pop_exact(), Some((1, 30)));
assert_eq!(queue.pop(), Some((5, 20)));
}
// ANCHOR_END: priority_queue
fn main() {
fifo_example();
priority_example();
let hive: ConcurrentAppendHive<usize> = ConcurrentAppendHive::new();
let keys: ConcurrentSparseSet<usize> = ConcurrentSparseSet::new();
std::thread::scope(|scope| {
for worker in 0..4 {
let (hive, keys) = (&hive, &keys);
scope.spawn(move || {
for value in worker * 4..(worker + 1) * 4 {
hive.insert(value);
keys.insert(value);
}
});
}
});
println!("hive count = {}", hive.len());
println!("set count = {}", keys.len());
let mut values: Vec<_> = hive.into_hive().values().copied().collect();
values.sort_unstable();
let mut contents: Vec<_> = keys.iter().copied().collect();
contents.sort_unstable();
println!("hive values = {values:?}");
println!("set keys = {contents:?}");
}
hive count = 16
set count = 16
hive values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
set keys = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
Containers
| Type | Shared (&self) | Exclusive (&mut self) | Lookups return |
|---|---|---|---|
ConcurrentHive<T> | insert, remove, take | iteration with &mut, drain, shrink_to_fit, into_hive | Ref guard (two atomic writes per lookup) |
ConcurrentAppendHive<T> | insert | remove, mutable access, shrink_to_fit, into_hive | &T (one Acquire load) |
ConcurrentPagedVec<T> | push | removal, editing, shrink_to_fit, conversion | &T |
ConcurrentQueue<T> (Python ConcurrentQueue) | push, pop | clear, drain, shrink_to_fit | owned value from pop |
ConcurrentPriorityQueue<K, P> (Python ConcurrentPriorityQueue, ConcurrentPriorityQueueF64) | push, change priority, remove, pop | clear, drain, shrink_to_fit | cloned priority or closure |
ConcurrentSparseSet<K>, ConcurrentSparseMap<K, V> | insert | removal, clear, drain, shrink_to_fit, conversion | &K, &V |
ConcurrentDirectMap<K, V> | insert, replace, remove, entry (per-page RwLock) | drain, shrink_to_fit, reset, into_inner | closures (with), clones (get_cloned), entry guards |
AtomicDirectMap (usize -> u64) | lock-free insert, update, remove | shrink_to_fit | copied u64 |
AtomicIdMap (Id -> u32) | lock-free insert, update, remove | shrink_to_fit | copied u32 |
ConcurrentIdAllocator | allocate, free, occupant, iter | clear | copied Id |
Notes per type:
- ConcurrentHive: a lookup guard pins its value until dropped; hot values
contend even between readers. Prefer the plain
Hivewhen shared mutation is not needed. - ConcurrentAppendHive: iteration may miss insertions in flight.
From<Hive>andinto_hivekeep live ids and stale-id history, in O(index bound). - Sparse set and map: entries cannot be removed or changed while shared.
shrink_to_fitfrees index pages with no entry and dense pages beyond the last entry; stored entries keep their addresses. Inserts of the same slot wait for its writer; other slots proceed independently. An occupied slot refuses other generations. Eachtry_insertreserves a dense position from one shared counter; under contention usetry_insert_many, which reserves once per batch.extendandcollectkeep the first occupant of each slot, including existing occupants when extending.drainyields owned items in dense order and keeps allocated pages for reuse. - ConcurrentDirectMap: neighbouring keys share a page lock and contend.
Release guards and entries before locking the same page again. Ordered
shared traversals are consistent per page only.
drainyields owned entries in key-index order and keeps allocated pages for reuse. - AtomicDirectMap, AtomicIdMap: prefer them over
ConcurrentDirectMapwhen values fit:u64values belowu64::MAX, or anyu32value keyed byId. Traversals copy values in index order.
The direct map and both atomic maps release empty pages with shrink_to_fit.
Flat directory chunks stay allocated. Radix collapses branches with only one
remaining child. Shared insertion can reinstall released pages.
Use for item in &collection on containers with iter and for item in &mut collection on containers with iter_mut. These loops use the same
item types, order and consistency as the respective iterator methods.
ConcurrentPagedVec
Concurrent pushes can finish out of order. A point lookup can read a published element beyond the first pending slot. Length, iteration and page slices all use the contiguous published prefix.
shrink_to_fit frees pages wholly beyond the vector’s length.
ConcurrentQueue
ConcurrentQueue is an unbounded multi-producer, multi-consumer FIFO queue,
adapted from Crossbeam’s SegQueue. It recycles pages through a free stack and
waits at page boundaries. A pop can also wait for a push that has claimed a
slot to publish its value. Shared peeking, iteration, cloning, snapshots and
serialization are unavailable; an owned queue can be converted to a
PagedDeque for serialization. The Python ConcurrentQueue holds Python
objects and drains into a list. See Python Threads
and the Python FIFO benchmarks.
#![allow(unused)]
fn main() {
fn fifo_example() {
use paged_collections::concurrent::ConcurrentQueue;
let queue = ConcurrentQueue::<_, 2>::new();
queue.push("first");
queue.push("second");
assert_eq!(queue.pop(), Some("first"));
assert_eq!(queue.pop(), Some("second"));
}
}
ConcurrentPriorityQueue
ConcurrentPriorityQueue is an indexed max-priority queue split into shards
by key page. Its pop is relaxed: it chooses the greatest of up to two sampled
shard tops, with a fallback scan, and does not guarantee the global maximum.
Use pop_exact to select the global maximum. Per-key operations lock one
shard; pop_exact locks all shards. Callbacks and user trait implementations
run under shard locks and must not call back into the same queue. The Python
classes ConcurrentPriorityQueue and ConcurrentPriorityQueueF64 store
numeric priorities and also support min queues. See Python Threads
and the Python priority-queue benchmarks.
pop returns. pop_exact locks all shards and selects the global maximum.#![allow(unused)]
fn main() {
fn priority_example() {
use paged_collections::concurrent::ConcurrentPriorityQueue;
let queue = ConcurrentPriorityQueue::<u32, i32, 4>::with_shards(3);
queue.push(1, 10);
queue.push(5, 20);
assert_eq!(queue.change_priority(&1, 30), Some(10));
assert_eq!(queue.pop_exact(), Some((1, 30)));
assert_eq!(queue.pop(), Some((5, 20)));
}
}
Directories
The sparse types, ConcurrentDirectMap and AtomicDirectMap take a
SharedDirectory parameter: Flat (default; O(1) page lookup, finite index
range) or Radix (any usize index, memory proportional to installed pages,
O(depth) lookup). AtomicIdMap is Flat-only; Tree has no concurrent form.
Id Allocation Under Contention
With std, freed slots go to one of 32 per-thread shards (no_std builds
use one shared stack), each with its own free stack
and block of fresh indices; a thread steals from other shards only when its
own is empty. A single-threaded caller takes an inline fast path. Measured
scaling is in Benchmarks.
occupant(index) reads the live generation at one index. Iterating over
&allocator scans live ids in index order up to the bound read at the start.
The scan takes no snapshot. Allocations and frees during iteration may or may
not be reflected, and a yielded id can already have been freed.
Element Invariance
Shared insertion requires every element type to be invariant: shortening a
stored reference’s lifetime would let a shorter-lived reference be inserted
while the owner still expects 'static. The containers are invariant in
their element types; compile-fail tests check this for each type.
Without std
Under no_std, the per-page locks of ConcurrentDirectMap spin. Lock guards
are !Send there.
API: concurrent.
Python Threads
Concurrent Classes
ConcurrentSparseSet, the typed ConcurrentSparseMap* classes (F64, F32,
I64, I32, U64, U32, Bool) and the typed ConcurrentDirectMap*
classes support shared access from threads.
| Sparse set and maps | Direct maps | |
|---|---|---|
| Shared inserts | set: insert, insert_many; maps: try_insert, get_or_insert, insert_many | m[k] = v, insert, try_insert, get_or_insert, setdefault, set_many |
| Shared removal | no | del m[k], remove, remove_many |
| Exclusive (conflicts raise) | remove, remove_many, clear, shrink_to_fit | clear, shrink_to_fit |
On a direct map, assignment, insert and set_many replace a stored value.
get_or_insert(key, value) and setdefault(key, value) atomically insert if
the key is absent and return the stored value. shrink_to_fit() (on every
concurrent set and map) frees pages with no live entries. Concurrent sparse map insertions keep existing values.
- Default page size and
Flatdirectory only; the constructors take nopage_size=. - Equality and hashing are by identity, unlike the other classes.
- Batch methods (
*_many) release the GIL; single-key calls do not. - Results are copies (arrays, lists); there are no guards or views.
- A conflicting exclusive call raises
RuntimeError("Already borrowed"). - Iteration visits a snapshot of keys with the same order and consistency as
keys(). The maps’contains_many(keys)returns a boolean array, treating invalid keys as absent just askey in mdoes. - Direct-map snapshots are in ascending key order.
items_range(start=None, stop=None),keys_rangeandvalues_rangecover the half-open interval[start, stop). Bounds are optional and clamped to the key domain. Likeitems(), each call is consistent within a page and weakly consistent across pages. len()is exact only when no write is in flight.ConcurrentSparseSet(keys)andConcurrentSparseMapF64(keys, values)accept NumPy arrays or sequences, validated before any write. Later duplicate keys win, even in the insert-only sparse maps.pickle,copy.copy,copy.deepcopyandcopy()take one snapshot, with the same consistency asitems(): entries inserted or removed during the call may or may not be included, but keys and values always pair up.
Example
from concurrent.futures import ThreadPoolExecutor
import numpy as np
from paged_collections import ConcurrentSparseMapF64
values = ConcurrentSparseMapF64()
def insert_chunk(worker):
keys = np.arange(worker * 1000, (worker + 1) * 1000, dtype=np.uint32)
return values.insert_many(keys, keys.astype(np.float64))
with ThreadPoolExecutor(max_workers=4) as pool:
inserted = list(pool.map(insert_chunk, range(4)))
print("inserted =", sum(inserted))
print("len =", len(values))
print("checksum =", float(values.values().sum()))
inserted = 4000
len = 4000
checksum = 7998000.0
ConcurrentQueue
ConcurrentQueue(iterable=None) holds Python objects in FIFO order. Threads
can share push, push_many, pop and pop_many. pop raises IndexError
when empty, and pop_many(n) returns up to n items, stopping at the first
empty pop. Length and truthiness are approximate during concurrent use and
exact when no operation is in flight.
clear(), drain() and shrink_to_fit() require exclusive access. If another
call holds a borrow, they raise RuntimeError("Already borrowed").
allocated_pages counts all allocated pages, including those pooled for reuse.
shrink_to_fit() frees pages the current values do not need and preserves FIFO
order. The queue has no iteration, peek, copy or pickle support. Use drain()
to move the items into a list in FIFO order before copying or pickling. Python’s
garbage collector cannot collect reference cycles through a queue.
Concurrent Priority Queues
ConcurrentPriorityQueue stores int64 priorities and
ConcurrentPriorityQueueF64 stores float64 priorities, with NaN rejected.
Both take integer keys in 0 <= key < 2**32. Pass min=True to prefer the
lowest priority and shards= to choose a shard count from 1 to 65536. The initial
items can be a mapping or iterable of pairs. Later duplicate keys win.
concurrent_priority_queue(dtype, items, min, shards=...) selects the class
by dtype.
push_increase(key, priority) and push_decrease(key, priority) insert an
absent key or update its priority only when the new numeric value is strictly
greater or strictly smaller, respectively, in either queue direction. The
methods return whether the queue changed.
pop() uses relaxed ordering. With multiple shards, the entry it returns
can rank below the global best. pop_exact() removes the global best and
peek_exact() reads it. Both exact operations lock all shards. Ties have
unspecified order. All three methods raise IndexError when they find no entry.
items(), sorted(), repr(), copying and pickling each read one snapshot.
It is consistent within each shard and weakly consistent across shards.
sorted() lists the best priorities first. The repr includes the class,
min, shards and up to 20 entries. Copies and pickles preserve min and
shards. Length and truthiness are exact when no write is in flight.
clear(), drain() and shrink_to_fit() require exclusive access and raise
RuntimeError("Already borrowed") if another call holds a borrow. drain()
returns all (key, priority) pairs in arbitrary order and keeps allocated
pages. shrink_to_fit() shrinks shard storage and frees the index pages of
empty shards.
Free-threaded CPython
Wheels exist for free-threaded 3.14t and 3.15t+ (see Installation). Importing the package keeps the GIL disabled, and the concurrent classes run in parallel.
The other classes are safe to share but are not designed for it: a call that
conflicts with another thread’s call on the same object raises
RuntimeError("Already borrowed"), or BufferError while views exist. Guard
shared use of those classes with a lock.
Zero-copy views (view(), keys_view(), values_view()) are not covered by
those checks: NumPy reads and writes their memory directly and may release
the GIL while doing so. Writing through a view while another thread reads or
writes the collection, or reading a view while another thread writes the
collection, is a data race, with or without the GIL. Hold the same lock for
the views as for the collection, or work on copies (keys(), values()).
Free-threaded 3.13t is not supported.
Scaling
benchmarks/python/concurrent_scaling.py measures batch throughput over
thread counts; results are in Benchmarks.
NumPy Interop
Keys
Integer-keyed classes (SparseSet, SparseMap*, DirectMap*, priority
queues) take keys in 0 <= key < 2**32 (KEY_LIMIT). IdMap* takes packed
uint64 ids. Keys may be Python ints or objects with __index__.
- Batch lookups (
contains_many,discard_many,get_many) treat out-of-range integers as absent, including arbitrarily large ints inside Python sequences or (for integer-keyed classes) object arrays.IdMap*batches reject object-dtype arrays. - Batch insertion (
add_many,set_many) rejects out-of-range keys. - The concurrent maps’
contains_manyaccepts an iterable or a one-dimensional array and reports invalid elements, including floats, as absent. Other batch lookup methods reject float key arrays.
Batch Methods
| Method | Input | Result |
|---|---|---|
add_many(keys) (set) | array-like of keys | number added |
set_many(keys, values) | keys, and values: typed maps take an array-like or a scalar to broadcast; object maps take an iterable | number of new keys |
get_many(keys, default) | keys | typed maps: array of the value dtype; object maps: list. Without a default, an absent key raises KeyError |
contains_many(keys) | keys | bool array |
discard_many(keys) | keys | number removed |
keys(), values() | arrays (copies); object maps return values as a list |
Batch methods run in one call into Rust. Native numeric arrays can avoid creating a Python object per element.
Typed Values
SparseMapF64, DirectMapF64, PagedListF64, IdMapF64 and the other typed
classes store values unboxed in the dtype named by the suffix: F64, F32,
I64, I32, U64, U32, Bool. sparse_map(dtype), direct_map(dtype),
id_map(dtype), paged_list(dtype), concurrent_sparse_map(dtype),
concurrent_direct_map(dtype) and priority_queue(dtype) create an instance
of the class for a dtype.
A dtype argument takes anything numpy.dtype accepts: "float64",
np.float64, np.dtype("f8") and float all select F64. Python’s int
means NumPy’s default integer, which is int32 on Windows with NumPy 1.x, so
name the width ("int64") for portable code.
Typed containers store values, not objects, so NaN != NaN as in NumPy: a typed container holding NaN does not compare equal even to itself.
Zero-Copy Views
| Method | Array | Writeable |
|---|---|---|
SparseSet.view() | dense keys, uint32 | no |
keys_view() (sparse and id maps) | dense keys | no |
values_view() (typed sparse and id maps) | dense values | yes, except Bool |
page_view(i), page_views() (typed lists) | one page of elements each | yes, except Bool |
Writes through a writeable view update the container. While any view is
alive, operations that would move or resize the underlying buffer raise
BufferError. Delete the view (or let it go out of scope) to release it.
A view’s base is an ExportGuard that keeps the container alive. NumPy
arrays are not tracked by Python’s garbage collector, so storing a view inside
the container it views (m[k] = m.keys_view()) makes a cycle that is never
freed.
Views bypass the borrow checks described in Python Threads: synchronise access to a view with access to its container when threads share them.
Direct maps have no views: their values live in pages, not one array.
Example
import numpy as np
from paged_collections import sparse_map
values = sparse_map("float64")
keys = np.array([7, 2, 9], dtype=np.uint32)
print("inserted =", values.set_many(keys, np.array([1.5, 2.5, 3.5])))
print("lookup =", values.get_many([9, 99, 7], default=-1.0).tolist())
view = values.values_view()
view *= 2
print("write through =", values.get_many(keys).tolist())
try:
values[100] = 4.5
except BufferError as error:
print("resize with view =", type(error).__name__)
del view
values[100] = 4.5
print("len after release =", len(values))
inserted = 3
lookup = [3.5, -1.0, 1.5]
write through = [3.0, 5.0, 7.0]
resize with view = BufferError
len after release = 4
Protocols
Pickle and Copy
Plain containers, concurrent maps and sets, and concurrent priority queues
support pickle, copy.copy and copy.deepcopy. Use ConcurrentQueue.drain()
to move FIFO contents into a list for copying or pickling.
- The page size is part of the pickled state. Pickles made before
page_size=existed load with page size 1024. HiveandIdAllocatorpickles keep generations and free slots, so ids stay valid across a round trip. AHiverebuilds its free lists on load, so the slot the next insert takes can differ from the original. Restoring an older pickle revives ids removed since it was taken (see Hive).- Concurrent maps, sets and priority queues pickle a snapshot of their contents (see Python threads).
Loading a pickle whose page size the running build does not include raises
ValueError (see page sizes).
Weak References
Every container class supports weakref.ref.
Subclassing
All container classes except the concurrent ones can be
subclassed. Pickle and copy keep the subclass, its __dict__ and its
__slots__ values (on 3.10 too, which lacks object.__getstate__).
Equality and Hashing
Plain containers compare by contents with ==. Concurrent containers compare
by identity. Concurrent maps, sets and FIFO queues hash by identity.
Plain containers and concurrent priority queues are unhashable.
Lists and deques also support <, <=, >, >= against the same class, as
list and deque do.
Collection ABCs
The package registers these classes with collections.abc for isinstance
and issubclass checks. Virtual registration keeps each class’s native methods
and return types.
| ABC | Classes |
|---|---|
MutableMapping | SparseMap, DirectMap, IdMap and their typed variants |
Mapping | Typed concurrent sparse and direct maps |
MutableSet | SparseSet and BitSet |
MutableSequence | PagedList and its typed variants |
Example
import pickle
import weakref
from paged_collections import SparseMap
class TaggedMap(SparseMap):
__slots__ = ("tag",)
values = SparseMap([7, 2], [10, 20], page_size=256)
restored = pickle.loads(pickle.dumps(values))
print("page size =", restored.page_size)
print("items =", restored.items())
reference = weakref.ref(values)
print("weakref alive =", reference() is values)
del values
print("weakref cleared =", reference() is None)
tagged = TaggedMap([9], [30], page_size=256)
tagged.tag = "scores"
restored_tagged = pickle.loads(pickle.dumps(tagged))
print("subclass =", type(restored_tagged).__name__)
print("slot =", restored_tagged.tag)
print("subclass page size =", restored_tagged.page_size)
print("subclass items =", restored_tagged.items())
page size = 256
items = [(7, 10), (2, 20)]
weakref alive = True
weakref cleared = True
subclass = TaggedMap
slot = scores
subclass page size = 256
subclass items = [(9, 30)]
Rust and Python Names
| Rust | Python | Python variants |
|---|---|---|
bit_set::PagedBitSet<u32> | BitSet | DEFAULT_BIT_PAGE_SIZE (64-bit words) |
sparse_set::PagedSparseSet<u32> | SparseSet | |
sparse_map::PagedSparseMap<u32, V> | SparseMap | SparseMapF64, F32, I64, I32, U64, U32, Bool; sparse_map(dtype) |
sparse_map::PagedSparseMap<Id, V> | IdMap | IdMapF64, …; id_map(dtype) |
direct_map::PagedDirectMap<u32, V> | DirectMap | DirectMapF64, …; direct_map(dtype) |
priority_queue::PagedPriorityQueue<u32, P> | PriorityQueue (int64), PriorityQueueF64 | min=True; priority_queue(dtype) |
paged_vec::PagedVec<T> | PagedList | PagedListF64, …; paged_list(dtype) |
paged_deque::PagedDeque<T> | PagedDeque | |
hive::Hive<T> | Hive | |
id_alloc::IdAllocator, Id | IdAllocator, packed int ids | id_index, id_generation, make_id, id_indices |
concurrent::ConcurrentSparseSet<u32> | ConcurrentSparseSet | |
concurrent::ConcurrentSparseMap<u32, V> | ConcurrentSparseMapF64, … | typed only; concurrent_sparse_map(dtype) |
concurrent::ConcurrentDirectMap<u32, V> | ConcurrentDirectMapF64, … | typed only; concurrent_direct_map(dtype) |
concurrent::ConcurrentHive, ConcurrentAppendHive, ConcurrentPagedVec, AtomicDirectMap, AtomicIdMap, ConcurrentIdAllocator | Rust only | |
PAGE const generic | page_size= keyword | PAGE_SIZES, DEFAULT_PAGE_SIZE |
page::Flat, Radix, Tree | always Flat |
Module constants: KEY_LIMIT (232), MAX_GENERATION (231),
MAX_INDICES.
Reference documentation:
- Rust: docs.rs/paged-collections
- Python:
_core.pyi(type stubs; also used by IDEs)
Benchmarks
These measurements come from one machine at the source revisions listed in Setup and Reproduction.
- Rust timings · Keyed collections · Priority queues · Vectors and deques · Generational ids
- Memory · Allocated bytes and shrinking · Page-size sweep
- Throughput · Thread scaling · Python queues
How to Read the Results
| Metric | What each value measures | Better |
|---|---|---|
| ns/key or ns/element | Median timed workload divided by the input size, n. Some workloads perform more or fewer than n calls. | Lower |
| ns/query | Median time per ordered query. A range query can visit many entries. | Lower |
| Bytes/key or MB | Live bytes requested from Rust’s global allocator at the stated checkpoint. MB is 1,000,000 bytes. | Lower |
| Throughput | The stated unit of work divided by median elapsed wall time, in millions per second. See each table for what counts as one unit. | Higher |
| Speedup | Throughput at the stated worker count divided by throughput for the same workload on one thread. | Higher |
In each timing table, n is the number of input entries or the starting
container size. A dash means no measurement is reported. Bold highlights the
lowest time in the Rust timing tables and the highest throughput in the
Python FIFO table. Small gaps on this machine are weak evidence of a
performance difference.
Comparison Implementations
| Workload | Baselines |
|---|---|
| Keyed maps and sets | hashbrown::HashMap and hashbrown::HashSet (0.17.1) with rustc_hash::FxHasher (2.1.3), plus Rust’s BTreeMap and BTreeSet. |
| Direct indexing | VecOption and VecBool are benchmark wrappers around Vec<Option<u64>> and Vec<bool>, respectively. They allocate one slot per index through the highest key and run only where that fits the harness’s size limit. |
| Rust priority queue | priority_queue::PriorityQueue (2.7.0), an indexed heap, and BinaryHeap, a standard-library heap with push and pop. |
| Sequences | Rust’s Vec and VecDeque. |
| Generational ids | SlotMap and DenseSlotMap (1.1.1), slab::Slab (0.4.12), and thunderdome::Arena (0.6.1). IdAllocatorIdMap is this package’s IdAllocator paired with a PagedSparseMap<Id, u64>. A slab uses reusable integer keys. |
| Python FIFO | CPython’s collections.deque and queue.SimpleQueue. |
| Python priority queues | CPython’s heapq on (priority, key) tuples, with a dictionary for lazy invalidation in the update workload or a threading.Lock for the multi-worker workload. |
Keyed Collections
These tables compare sparse maps, sparse sets,
and direct maps with the linked baseline implementations.
PagedDirectMapFlat and PagedDirectMapRadix use the same map with different
page directories.
| Workload | Timed work |
|---|---|
| Insert | Build from n keys in pattern order, including allocation. |
| Hit | Look up each present key once in shuffled order. |
| Miss | Look up n absent keys from a disjoint part of the same pattern. |
| Iterate | Traverse the entries and fold them into a checksum. |
| Remove | Remove all keys from a prebuilt container in shuffled order. |
Dense keys are 0..n. Clustered keys form runs of 64 consecutive
integers with run starts spread across the u32 range. Uniform keys come
from a pseudo-random permutation of u32. The harness skips the 10⁷-key
uniform cases because of the cost of allocating and initializing many pages.
For 10⁵ dense keys, the flat direct map took 4.25 ns/hit against 10.9 for
hashbrown, and the sparse map iterated at 0.265 ns/entry against 1.84.
For 10⁵ uniform keys, hashbrown inserted at 33.1 ns/key in the sparse-map
comparison, against 3,345 for the sparse map. Use the key pattern closest to
your workload when reading the tables.
Sparse Map (u32 -> u64)
Dense keys (ns/key)
| n, op | PagedSparseMap | HashMap | BTreeMap | VecOption |
|---|---|---|---|---|
| 10³ insert | 6.44 | 24.1 | 75.2 | 4.7 |
| 10³ hit | 2.8 | 5.26 | 45.6 | 1.15 |
| 10³ miss | 1.24 | 4.13 | 24.4 | 0.779 |
| 10³ iterate | 0.155 | 2.02 | 2.76 | 0.578 |
| 10³ remove | 8.02 | 10.4 | 93.5 | 1.05 |
| 10⁵ insert | 6.05 | 33.9 | 99.8 | 6.42 |
| 10⁵ hit | 8.94 | 11 | 132 | 2.57 |
| 10⁵ miss | 1.18 | 8 | 42.8 | 0.803 |
| 10⁵ iterate | 0.265 | 1.84 | 3.05 | 0.699 |
| 10⁵ remove | 23.2 | 16.8 | 178 | 19.8 |
| 10⁷ insert | 14 | 130 | 145 | 14.2 |
| 10⁷ hit | 47.9 | 42.3 | 450 | 14.5 |
| 10⁷ miss | 1.18 | 8.42 | 66.5 | 0.826 |
| 10⁷ iterate | 0.907 | 3.86 | 8.87 | 2.27 |
| 10⁷ remove | 194 | 141 | 543 | 107 |
Clustered keys (ns/key)
| n, op | PagedSparseMap | HashMap | BTreeMap | VecOption |
|---|---|---|---|---|
| 10³ insert | 41.1 | 25.8 | 75.6 | 57.4 |
| 10³ hit | 2.94 | 5.23 | 49.6 | 1.15 |
| 10³ miss | 1.22 | 4.15 | 28.6 | 0.762 |
| 10³ iterate | 0.155 | 1.82 | 2.75 | 18,291 |
| 10³ remove | 24.4 | 10.4 | 93.5 | 20.4 |
| 10⁵ insert | 212 | 32.6 | 116 | – |
| 10⁵ hit | 15.6 | 11.3 | 134 | – |
| 10⁵ miss | 1.53 | 7.73 | 35 | – |
| 10⁵ iterate | 0.263 | 1.83 | 3.23 | – |
| 10⁵ remove | 109 | 22 | 179 | – |
| 10⁷ insert | 56.8 | 140 | 147 | – |
| 10⁷ hit | 60.3 | 41.5 | 467 | – |
| 10⁷ miss | 2.89 | 13.2 | 51.5 | – |
| 10⁷ iterate | 0.894 | 3.9 | 9.91 | – |
| 10⁷ remove | 307 | 129 | 573 | – |
Uniform keys (ns/key)
Sparse Set (u32)
Dense keys (ns/key)
| n, op | PagedSparseSet | HashSet | BTreeSet | VecBool |
|---|---|---|---|---|
| 10³ insert | 6.2 | 21.9 | 63.9 | 3.47 |
| 10³ hit | 2.69 | 4.82 | 48.7 | 0.967 |
| 10³ miss | 1.01 | 4.47 | 24.7 | 0.878 |
| 10³ iterate | 0.207 | 1.68 | 2.78 | 0.571 |
| 10³ remove | 4.66 | 11 | 85.3 | 0.906 |
| 10⁵ insert | 5.69 | 28.5 | 89.3 | 3.32 |
| 10⁵ hit | 6.7 | 9.82 | 128 | 1.24 |
| 10⁵ miss | 0.995 | 7.83 | 42.7 | 0.872 |
| 10⁵ iterate | 0.211 | 1.57 | 2.93 | 0.558 |
| 10⁵ remove | 11.7 | 16.4 | 157 | 5.78 |
| 10⁷ insert | 9.49 | 57 | 120 | 3.55 |
| 10⁷ hit | 31.1 | 36.1 | 366 | 3.88 |
| 10⁷ miss | 1.01 | 7.93 | 66.5 | 0.887 |
| 10⁷ iterate | 0.341 | 1.93 | 4.91 | 0.565 |
| 10⁷ remove | 128 | 113 | 433 | 21.5 |
Clustered keys (ns/key)
| n, op | PagedSparseSet | HashSet | BTreeSet | VecBool |
|---|---|---|---|---|
| 10³ insert | 41.5 | 23.8 | 64.1 | 1,557 |
| 10³ hit | 2.74 | 4.83 | 48.6 | 0.952 |
| 10³ miss | 0.999 | 4.48 | 24.3 | 0.878 |
| 10³ iterate | 0.207 | 1.54 | 2.78 | 17,803 |
| 10³ remove | 20.7 | 11 | 78.9 | 1.43 |
| 10⁵ insert | 207 | 27 | 91.3 | – |
| 10⁵ hit | 11.8 | 10.1 | 130 | – |
| 10⁵ miss | 1.26 | 7.67 | 34.8 | – |
| 10⁵ iterate | 0.21 | 1.78 | 3.02 | – |
| 10⁵ remove | 99.8 | 21.9 | 157 | – |
| 10⁷ insert | 46.5 | 75 | 148 | – |
| 10⁷ hit | 42.1 | 38.1 | 394 | – |
| 10⁷ miss | 2.63 | 12.2 | 55 | – |
| 10⁷ iterate | 0.343 | 2.3 | 9.31 | – |
| 10⁷ remove | 238 | 109 | 437 | – |
Uniform keys (ns/key)
Direct Map (u32 -> u64)
Dense keys (ns/key)
| n, op | PagedDirectMapFlat | PagedDirectMapRadix | HashMap | BTreeMap | VecOption |
|---|---|---|---|---|---|
| 10³ insert | 4.69 | 7.3 | 24.7 | 80.1 | 4.62 |
| 10³ hit | 2.37 | 2.38 | 5 | 45.1 | 1.15 |
| 10³ miss | 1.21 | 1.2 | 4.11 | 24.4 | 0.764 |
| 10³ iterate | 2.25 | 2.55 | 1.72 | 2.76 | 0.564 |
| 10³ remove | 2.31 | 2.6 | 10.4 | 93.9 | 1.06 |
| 10⁵ insert | 5.13 | 7.66 | 33.9 | 111 | 6.41 |
| 10⁵ hit | 4.25 | 4.26 | 10.9 | 131 | 2.56 |
| 10⁵ miss | 1.19 | 1.18 | 8 | 42.8 | 0.801 |
| 10⁵ iterate | 2.25 | 2.54 | 1.61 | 3.08 | 0.692 |
| 10⁵ remove | 4.1 | 4.53 | 17.1 | 178 | 19.7 |
| 10⁷ insert | 7 | 16.3 | 131 | 147 | 14.2 |
| 10⁷ hit | 19.2 | 19.3 | 42.1 | 451 | 14.6 |
| 10⁷ miss | 1.2 | 1.2 | 8.01 | 66.3 | 0.828 |
| 10⁷ iterate | 2.56 | 2.82 | 3.83 | 9.54 | 2.26 |
| 10⁷ remove | 29.3 | 30.4 | 140 | 539 | 106 |
Clustered keys (ns/key)
| n, op | PagedDirectMapFlat | PagedDirectMapRadix | HashMap | BTreeMap | VecOption |
|---|---|---|---|---|---|
| 10³ insert | 50.8 | 38.5 | 26.4 | 81.3 | 56.4 |
| 10³ hit | 2.49 | 17 | 4.91 | 45.1 | 1.15 |
| 10³ miss | 1.2 | 2.62 | 4.12 | 24.4 | 0.763 |
| 10³ iterate | 60.2 | 39.9 | 1.55 | 2.74 | 18,305 |
| 10³ remove | 19.1 | 18.2 | 10.3 | 94 | 20.8 |
| 10⁵ insert | 249 | 99.2 | 32.6 | 115 | – |
| 10⁵ hit | 10.5 | 37.7 | 11 | 133 | – |
| 10⁵ miss | 1.53 | 13 | 7.49 | 35.1 | – |
| 10⁵ iterate | 75.1 | 39.9 | 1.79 | 3.25 | – |
| 10⁵ remove | 84.1 | 41.5 | 22.1 | 179 | – |
| 10⁷ insert | 161 | 200 | 128 | 142 | – |
| 10⁷ hit | 26.7 | 108 | 41.5 | 468 | – |
| 10⁷ miss | 2.85 | 16.5 | 12.7 | 49.3 | – |
| 10⁷ iterate | 33.2 | 47.4 | 3.91 | 10.3 | – |
| 10⁷ remove | 177 | 196 | 125 | 569 | – |
Uniform keys (ns/key)
| n, op | PagedDirectMapFlat | PagedDirectMapRadix | HashMap | BTreeMap | VecOption |
|---|---|---|---|---|---|
| 10³ insert | 8,687 | 6,401 | 27 | 85.3 | – |
| 10³ hit | 4.61 | 21 | 5.16 | 47 | – |
| 10³ miss | 1.19 | 2.62 | 5 | 24.7 | – |
| 10³ iterate | 1,208 | 2,489 | 1.56 | 3.04 | – |
| 10³ remove | 1,065 | 807 | 10.6 | 94.4 | – |
| 10⁵ insert | 10,974 | 11,033 | 33 | 113 | – |
| 10⁵ hit | 23.3 | 69.1 | 11.1 | 132 | – |
| 10⁵ miss | 3.95 | 26.1 | 10.4 | 78 | – |
| 10⁵ iterate | 2,093 | 3,001 | 1.79 | 3.67 | – |
| 10⁵ remove | 1,484 | 1,062 | 22.6 | 173 | – |
Ordered Queries
The input is dense. Each measurement issues 1,000 queries from shuffled
starting keys and reports ns/query. next finds the first entry at or
after the starting key, using BTreeMap::range(k..).next() for the
baseline. range_1000 visits entries within a 1,000-key window. Windows
near the end of the input can contain fewer entries.
| n, query | PagedDirectMapFlat | PagedDirectMapRadix | BTreeMap |
|---|---|---|---|
| 10³ next | 18.7 | 39.5 | 52.2 |
| 10⁵ next | 20.2 | 42.4 | 129 |
| 10⁷ next | 21.9 | 44.9 | 270 |
| 10³ range_1000 | 3,967 | 2,970 | 1,324 |
| 10⁵ range_1000 | 7,930 | 5,799 | 2,989 |
| 10⁷ range_1000 | 8,012 | 5,863 | 3,252 |
At 10⁵ keys, a flat direct-map next query took 20.2 ns versus 129 ns
for the B-tree. At the same size, scanning the window took 7,930 ns
for the flat direct map and 2,989 ns for the B-tree.
Memory
Tables report bytes/key after building the container: live allocator
bytes above the pre-build baseline divided by n. Input key arrays are
allocated before that baseline. RSS, allocator bookkeeping and temporary
peak allocations are outside this metric.
Sparse Map
| pattern, n | PagedSparseMap | HashMap | BTreeMap | VecOption |
|---|---|---|---|---|
| dense 10³ | 16.4 | 34.8 | 26.4 | 16 |
| dense 10⁵ | 19.8 | 22.3 | 26.3 | 16 |
| dense 10⁷ | 24.1 | 28.5 | 26.3 | 16 |
| clustered 10³ | 343 | 34.8 | 26.4 | 506,344 |
| clustered 10⁵ | 419 | 22.3 | 25.8 | – |
| clustered 10⁷ | 87.5 | 28.5 | 25.8 | – |
| uniform 10³ | 6,279 | 34.8 | 24.3 | – |
| uniform 10⁵ | 4,459 | 22.3 | 19.7 | – |
Sparse Set
| pattern, n | PagedSparseSet | HashSet | BTreeSet | VecBool |
|---|---|---|---|---|
| dense 10³ | 8.22 | 10.3 | 11.7 | 1 |
| dense 10⁵ | 9.27 | 6.55 | 11.6 | 1 |
| dense 10⁷ | 10.7 | 8.39 | 11.6 | 1 |
| clustered 10³ | 335 | 10.3 | 11.7 | 31,647 |
| clustered 10⁵ | 409 | 6.55 | 11.3 | – |
| clustered 10⁷ | 74.1 | 8.39 | 11.3 | – |
| uniform 10³ | 6,271 | 10.3 | 10.7 | – |
| uniform 10⁵ | 4,449 | 6.55 | 8.53 | – |
Direct Map
| pattern, n | PagedDirectMapFlat | PagedDirectMapRadix | HashMap | BTreeMap | VecOption |
|---|---|---|---|---|---|
| dense 10³ | 16.4 | 16.4 | 34.8 | 26.4 | 16 |
| dense 10⁵ | 16.1 | 16.1 | 22.3 | 26.3 | 16 |
| dense 10⁷ | 16 | 16 | 28.5 | 26.3 | 16 |
| clustered 10³ | 527 | 263 | 34.8 | 26.4 | 506,344 |
| clustered 10⁵ | 596 | 257 | 22.3 | 25.8 | – |
| clustered 10⁷ | 259 | 260 | 28.5 | 25.8 | – |
| uniform 10³ | 18,555 | 16,435 | 34.8 | 24.3 | – |
| uniform 10⁵ | 16,731 | 16,639 | 22.3 | 19.7 | – |
In this run a sparse index page used 4 bytes per slot and a direct-map page
used 16 bytes per slot (u32 -> u64). A single 64-key run fills 6% of a
1,024-slot page. Widely scattered keys leave many pages with just a few live
slots. The directory and any dense arrays also contribute to the total.
Removal and Shrinking
The harness builds each container, randomly removes 90% of its entries, then
calls shrink_to_fit where available. The three columns show live allocations
in MB at those checkpoints. BTreeMap frees nodes during removal.
The Hive row also includes the benchmark’s vector of ids kept for removal.
| Container | Pattern | n | Built | After removal | After shrink |
|---|---|---|---|---|---|
| PagedSparseMap | uniform | 10⁵ | 445.9 | 445.9 | 443.3 |
| PagedDirectMapFlat | uniform | 10⁵ | 1,673.1 | 1,673.1 | 197.4 |
| PagedDirectMapRadix | uniform | 10⁵ | 1,663.9 | 1,663.9 | 170.1 |
HashMap | uniform | 10⁵ | 2.2 | 2.2 | 0.3 |
BTreeMap | uniform | 10⁵ | 2.0 | 0.2 | 0.2 |
| PagedSparseMap | dense | 10⁷ | 241.5 | 241.5 | 52.1 |
| PagedDirectMapFlat | dense | 10⁷ | 160.1 | 160.1 | 160.1 |
| PagedDirectMapRadix | dense | 10⁷ | 160.1 | 160.1 | 160.1 |
HashMap | dense | 10⁷ | 285.2 | 285.2 | 35.7 |
BTreeMap | dense | 10⁷ | 262.9 | 22.7 | 22.7 |
| PagedSparseMap | clustered | 10⁷ | 875.3 | 875.3 | 685.6 |
| PagedDirectMapFlat | clustered | 10⁷ | 2,594.0 | 2,594.0 | 2,590.6 |
| PagedDirectMapRadix | clustered | 10⁷ | 2,603.6 | 2,603.6 | 2,592.8 |
HashMap | clustered | 10⁷ | 285.2 | 285.2 | 35.7 |
BTreeMap | clustered | 10⁷ | 257.7 | 22.7 | 22.7 |
| Hive | sequential | 10⁷ | 240.7 | 240.8 | 240.5 |
For uniform keys at 10⁵ entries, the flat direct map dropped from 1,673.1 MB to 197.4 MB after shrinking. For dense 10⁷ keys, almost every page still contained survivors, and memory held at 160.1 MB. The sparse map can shrink its dense arrays even when index pages remain allocated.
Page Size
The sweep changes the number of slots per page with Flat at 10⁵ keys.
Timing is the median of seven samples divided by n. Bytes/key uses the
live size after construction, also divided by n.
Sparse Map
| Pattern | Measure | PAGE=64 | PAGE=256 | PAGE=1024 | PAGE=4096 | PAGE=16384 |
|---|---|---|---|---|---|---|
| dense | insert ns/key | 11.3 | 11.1 | 10.6 | 10.4 | 10.5 |
| dense | hit ns/key | 11.8 | 11.6 | 11.4 | 11.4 | 11.4 |
| dense | iterate ns/key | 0.266 | 0.267 | 0.266 | 0.266 | 0.267 |
| dense | bytes/key | 19.9 | 19.8 | 19.8 | 19.8 | 20.3 |
| clustered | insert ns/key | 2,632 | 669 | 187 | 40 | 602 |
| clustered | hit ns/key | 17.5 | 18.1 | 19 | 19.2 | 18.1 |
| clustered | iterate ns/key | 0.266 | 0.266 | 0.266 | 0.267 | 0.267 |
| clustered | bytes/key | 5,452 | 1,390 | 419 | 357 | 1,061 |
| uniform | insert ns/key | 3,643 | 1,278 | 2,536 | 9,926 | 26,248 |
| uniform | hit ns/key | 27.5 | 28.9 | 28 | 25.6 | 24 |
| uniform | iterate ns/key | 0.267 | 0.267 | 0.266 | 0.267 | 0.267 |
| uniform | bytes/key | 5,810 | 2,425 | 4,459 | 16,488 | 42,988 |
Direct Map
| Pattern | Measure | PAGE=64 | PAGE=256 | PAGE=1024 | PAGE=4096 | PAGE=16384 |
|---|---|---|---|---|---|---|
| dense | insert ns/key | 6.04 | 5.19 | 5.02 | 5.02 | 5.47 |
| dense | hit ns/key | 5.85 | 5.72 | 5.67 | 5.67 | 5.67 |
| dense | iterate ns/key | 2.24 | 2.24 | 2.25 | 2.25 | 2.25 |
| dense | bytes/key | 16.2 | 16.1 | 16.1 | 16.4 | 18.4 |
| clustered | insert ns/key | 2,615 | 663 | 210 | 592 | 2,384 |
| clustered | hit ns/key | 10.1 | 11.9 | 12.3 | 12.4 | 10.4 |
| clustered | iterate ns/key | 1,002 | 262 | 87.8 | 136 | 481 |
| clustered | bytes/key | 5,448 | 1,422 | 596 | 1,109 | 4,119 |
| uniform | insert ns/key | 3,797 | 3,251 | 9,695 | 37,356 | – |
| uniform | hit ns/key | 26.5 | 27.1 | 23.7 | 21.8 | – |
| uniform | iterate ns/key | 1,504 | 899 | 2,106 | 7,753 | – |
| uniform | bytes/key | 6,562 | 5,481 | 16,731 | 65,624 | – |
Small pages waste less memory per partly filled page, but with Flat the
directory holds one pointer for each page up to the highest key: for keys
spread over the u32 range, PAGE = 64 makes a 512 MiB directory, which
dominates the memory column. 1024 is the default because it is close to the
best across patterns. On dense keys the page size barely matters.
Priority Queue
The Rust paged priority queue and the priority-queue crate
both support priority changes by key. BinaryHeap runs only
the push and pop cases. Each value is ns per input element.
| Workload | Timed work |
|---|---|
push | Build by pushing n entries into an empty heap. |
change_priority | Change n/2 priorities in a prebuilt heap. The table divides by n; multiply by two for ns per update. |
pop_all | Drain a prebuilt heap in priority order, stopping at empty. |
| n, op | PagedPriorityQueue | priority-queue | BinaryHeap |
|---|---|---|---|
| 10³ push | 18.1 | 64 | 7.74 |
| 10⁵ push | 17.8 | 111 | 9.72 |
| 10⁷ push | 28.9 | 390 | 20.7 |
| 10³ change_priority | 7.39 | 28.7 | – |
| 10⁵ change_priority | 18.4 | 85.4 | – |
| 10⁷ change_priority | 145 | 551 | – |
| 10³ pop_all | 71.1 | 109 | 48.3 |
| 10⁵ pop_all | 161 | 319 | 155 |
| 10⁷ pop_all | 632 | 2,329 | 564 |
At 10⁵ entries, the paged heap took 17.8 ns/element to push versus
111 for the indexed crate and 9.72 for BinaryHeap. Its priority changes
took 18.4 ns per input element versus 85.4 for the indexed crate.
Paged Vector and Deque
Timings are ns per input element. The vector’s random_get and the
deque’s random_index each look up n shuffled positions. One
queue_churn step is a front pop followed by a back push, repeated n
times on a full deque.
Vector
| n, op | PagedVec | Vec |
|---|---|---|
| 10³ push | 2.85 | 2.29 |
| 10⁵ push | 2.95 | 1.68 |
| 10⁷ push | 7.96 | 5.09 |
| 10³ random_get | 2.23 | 1.21 |
| 10⁵ random_get | 2.23 | 1.21 |
| 10⁷ random_get | 3.22 | 1.4 |
| 10³ iterate | 0.394 | 0.381 |
| 10⁵ iterate | 0.394 | 0.372 |
| 10⁷ iterate | 0.395 | 0.372 |
| 10³ sum | 0.487 | 0.155 |
| 10⁵ sum | 0.512 | 0.266 |
| 10⁷ sum | 1.05 | 0.9 |
Deque
| n, op | PagedDeque | VecDeque |
|---|---|---|
| 10³ push_front | 4.96 | 3.84 |
| 10⁵ push_front | 5.62 | 3.34 |
| 10⁷ push_front | 9.78 | 9.73 |
| 10³ queue_churn | 8.8 | 4.98 |
| 10⁵ queue_churn | 8.27 | 4.94 |
| 10⁷ queue_churn | 9.04 | 9.17 |
| 10³ random_index | 2.52 | 1.74 |
| 10⁵ random_index | 2.51 | 1.73 |
| 10⁷ random_index | 2.68 | 1.87 |
Iteration matches Vec. Indexing costs one extra indirection (1 to 2 ns).
At 10⁷ elements the deque is level with VecDeque, whose growth copies
every element; at small sizes VecDeque is faster.
Generational Ids
Timings are ns per input element. insert builds n entries, get
looks up all ids in shuffled order, and iterate visits the live entries.
remove_half_reinsert removes half the original entries and inserts as many
again. See the baseline descriptions for the
different handle types.
| n, op | Hive | IdAllocatorIdMap | SlotMap | DenseSlotMap | Slab | Arena |
|---|---|---|---|---|---|---|
| 10³ insert | 9.3 | 19.3 | 7.73 | 12.9 | 7.76 | 6.37 |
| 10⁵ insert | 15.6 | 18.1 | 8.27 | 12.3 | 7.97 | 7.93 |
| 10⁷ insert | 24.3 | 35.9 | 20.1 | 29.5 | 19.7 | 19.9 |
| 10³ get | 4.19 | 4.84 | 2.92 | 3.37 | 1.7 | 2.61 |
| 10⁵ get | 6.94 | 11.5 | 5.2 | 7.19 | 3.33 | 4.08 |
| 10⁷ get | 31 | 59 | 22.4 | 36.9 | 16.9 | 18.3 |
| 10³ iterate | 0.884 | 0.156 | 1.4 | 0.46 | 0.885 | 0.882 |
| 10⁵ iterate | 0.985 | 0.264 | 1.4 | 0.501 | 0.884 | 0.931 |
| 10⁷ iterate | 2.34 | 0.895 | 2.36 | 1.05 | 2.32 | 2.36 |
| 10³ remove_half_reinsert | 8.6 | 15.8 | 3.71 | 6.5 | 3.73 | 4.92 |
| 10⁵ remove_half_reinsert | 12.1 | 34 | 13.1 | 29.5 | 13.2 | 14.5 |
| 10⁷ remove_half_reinsert | 41.9 | 293 | 67.1 | 179 | 67.7 | 72.2 |
Hive keeps elements at stable addresses and pays for it on raw lookup speed
against slotmap, slab and thunderdome, which store values in one growable
vector. IdAllocator + PagedSparseMap also keeps values in a dense vector,
so removal can move the last value; its cost is the extra index lookup.
Concurrent Scaling
Rust
The Rust scaling harness uses 2 million shuffled keys as work items and splits them across workers. The table divides the count of work items by the median of seven wall times. One item is one key or id processed, or one increment in the shared-counter reference. Churn counts insertions or allocations, with removal or freeing included in the timer. A batch call counts each key it processes.
Throughput in millions of work items/s. Each workload uses its own one-thread run as the speedup baseline.
| Workload | 1 thread | 2 threads | 4 threads | 8 threads | 4-thread speedup |
|---|---|---|---|---|---|
| sparse try_insert (fresh) | 9.4 | 4.4 | 3.5 | 3.3 | 0.38x |
| sparse try_insert_many (fresh) | 19.1 | 37.3 | 72.7 | 119.2 | 3.81x |
| sparse get | 31.4 | 61.0 | 115.8 | 229.2 | 3.68x |
| direct insert (fresh) | 18.8 | 27.8 | 46.6 | 85.4 | 2.48x |
| direct insert (overwrite) | 23.6 | 35.8 | 61.5 | 109.0 | 2.60x |
| direct get | 15.8 | 23.1 | 39.9 | 72.8 | 2.52x |
| atomic direct insert (fresh) | 25.0 | 47.1 | 91.3 | 178.6 | 3.66x |
| hive insert (fresh) | 19.7 | 40.2 | 78.2 | 143.6 | 3.97x |
| hive remove | 6.6 | 12.8 | 24.7 | 48.4 | 3.74x |
| hive churn (64 live per thread) | 12.6 | 21.7 | 32.1 | 52.8 | 2.54x |
| append hive insert (fresh) | 22.9 | 40.6 | 77.2 | 141.2 | 3.37x |
| id allocate (fresh) | 28.6 | 56.4 | 114.7 | 216.5 | 4.01x |
| id free | 10.1 | 19.3 | 37.3 | 71.2 | 3.71x |
| id churn (64 live per thread) | 12.6 | 21.8 | 30.6 | 52.1 | 2.43x |
| shared counter fetch_add only | 141.1 | 49.1 | 50.2 | 51.4 | 0.36x |
Single-key try_insert into a fresh sparse map does not scale: every insert
reserves a dense-array position from one shared counter, so threads contend
on it. try_insert_many takes one reservation per batch and scales. The last row is a
single shared fetch_add counter, as a reference for cache-line contention.
Python
The Python scaling harness splits 2 million shuffled keys
among workers using typed float64 maps and batch calls. The median of
seven elapsed wall times includes dispatch, NumPy copies and creation of
the returned arrays. Speedup compares the same map and operation against
one worker on the same Python build.
Free-threaded CPython 3.14.10 (GIL disabled)
| Class | Operation | Threads | Median (s) | Throughput (M keys/s) | Speedup |
|---|---|---|---|---|---|
| ConcurrentDirectMapF64 | get_many | 1 | 0.192651 | 10.38 | 1.00x |
| ConcurrentDirectMapF64 | get_many | 2 | 0.111697 | 17.91 | 1.72x |
| ConcurrentDirectMapF64 | get_many | 4 | 0.061031 | 32.77 | 3.16x |
| ConcurrentDirectMapF64 | get_many | 8 | 0.039717 | 50.36 | 4.85x |
| ConcurrentDirectMapF64 | set_many | 1 | 0.117383 | 17.04 | 1.00x |
| ConcurrentDirectMapF64 | set_many | 2 | 0.081900 | 24.42 | 1.43x |
| ConcurrentDirectMapF64 | set_many | 4 | 0.048361 | 41.36 | 2.43x |
| ConcurrentDirectMapF64 | set_many | 8 | 0.027625 | 72.40 | 4.25x |
| ConcurrentSparseMapF64 | get_many | 1 | 0.105083 | 19.03 | 1.00x |
| ConcurrentSparseMapF64 | get_many | 2 | 0.055440 | 36.08 | 1.90x |
| ConcurrentSparseMapF64 | get_many | 4 | 0.037057 | 53.97 | 2.84x |
| ConcurrentSparseMapF64 | get_many | 8 | 0.025559 | 78.25 | 4.11x |
| ConcurrentSparseMapF64 | insert_many | 1 | 0.138173 | 14.47 | 1.00x |
| ConcurrentSparseMapF64 | insert_many | 2 | 0.062856 | 31.82 | 2.20x |
| ConcurrentSparseMapF64 | insert_many | 4 | 0.034273 | 58.36 | 4.03x |
| ConcurrentSparseMapF64 | insert_many | 8 | 0.021569 | 92.73 | 6.41x |
CPython 3.12.16 (GIL enabled)
| Class | Operation | Threads | Median (s) | Throughput (M keys/s) | Speedup |
|---|---|---|---|---|---|
| ConcurrentDirectMapF64 | get_many | 1 | 0.174405 | 11.47 | 1.00x |
| ConcurrentDirectMapF64 | get_many | 2 | 0.109154 | 18.32 | 1.60x |
| ConcurrentDirectMapF64 | get_many | 4 | 0.066318 | 30.16 | 2.63x |
| ConcurrentDirectMapF64 | get_many | 8 | 0.048947 | 40.86 | 3.56x |
| ConcurrentDirectMapF64 | set_many | 1 | 0.141601 | 14.12 | 1.00x |
| ConcurrentDirectMapF64 | set_many | 2 | 0.092276 | 21.67 | 1.53x |
| ConcurrentDirectMapF64 | set_many | 4 | 0.056619 | 35.32 | 2.50x |
| ConcurrentDirectMapF64 | set_many | 8 | 0.039759 | 50.30 | 3.56x |
| ConcurrentSparseMapF64 | get_many | 1 | 0.092247 | 21.68 | 1.00x |
| ConcurrentSparseMapF64 | get_many | 2 | 0.050604 | 39.52 | 1.82x |
| ConcurrentSparseMapF64 | get_many | 4 | 0.046505 | 43.01 | 1.98x |
| ConcurrentSparseMapF64 | get_many | 8 | 0.028807 | 69.43 | 3.20x |
| ConcurrentSparseMapF64 | insert_many | 1 | 0.142124 | 14.07 | 1.00x |
| ConcurrentSparseMapF64 | insert_many | 2 | 0.066021 | 30.29 | 2.15x |
| ConcurrentSparseMapF64 | insert_many | 4 | 0.040706 | 49.13 | 3.49x |
| ConcurrentSparseMapF64 | insert_many | 8 | 0.036124 | 55.37 | 3.93x |
With the GIL, batch calls still overlap because they release it while in Rust; the free-threaded build also runs the Python-side dispatch in parallel.
Python Queues
The queue harness uses 1 million input items and reports
throughput from the median of five wall times. 3.12 is CPython 3.12.16
with the GIL enabled. 3.14t is CPython 3.14.10 with the GIL disabled.
Throughput units differ across workloads.
FIFO
Millions of items/s. Each item counts once for a push followed by a
pop. The single-thread case fills the queue then drains it. Multi-thread
cases use equal numbers of producers and consumers working concurrently.
SimpleQueue consumers block in get(). The other consumers retry an
empty queue. The batch column uses push_many and pop_many in batches of
up to 1,024 items.
| Case | Python | deque | SimpleQueue | ConcurrentQueue | ConcurrentQueue batch |
|---|---|---|---|---|---|
| 1 thread | 3.12 | 16.29 | 12.24 | 6.05 | 12.64 |
| 1 thread | 3.14t | 8.90 | 7.30 | 5.20 | 11.75 |
| 4 + 4 threads | 3.12 | 3.49 | 4.49 | 1.81 | 6.23 |
| 4 + 4 threads | 3.14t | 3.49 | 3.32 | 2.89 | 5.58 |
| 8 + 8 threads | 3.12 | 3.89 | 4.55 | 2.19 | 6.08 |
| 8 + 8 threads | 3.14t | 0.42 | 0.71 | 1.75 | 5.62 |
At 8 producers and 8 consumers on free-threaded CPython, the per-item
ConcurrentQueue path processed 1.75 M items/s and the batch path processed
5.62 M items/s. For single-threaded scalar calls, deque led on both builds.
Priority Queues
All runs use distinct integer keys with random float priorities in min-queue
mode. PriorityQueueF64 and
ConcurrentPriorityQueueF64 update existing keys in place.
The concurrent queue’s pop uses relaxed ordering. Use the pop_exact
column when comparing global-priority removal with heapq in the
single-thread push-and-drain workload.
Push and Drain
Millions of items/s. A single thread pushes all items, then drains the queue. Each item counts once across both phases.
| Python | heapq | PriorityQueueF64 | Concurrent pop | Concurrent pop_exact |
|---|---|---|---|---|
| 3.12 | 0.21 | 0.70 | 0.64 | 0.22 |
| 3.14t | 0.23 | 0.89 | 0.83 | 0.24 |
Update Existing Priorities
Millions of writes/s. The numerator counts the initial n pushes and
n/2 priority changes. Elapsed time also includes draining the queue.
heapq pushes a new tuple for each change and skips stale tuples during
the drain using a dictionary of current priorities.
| Python | heapq + lazy invalidation | PriorityQueueF64 | Concurrent pop |
|---|---|---|---|
| 3.12 | 0.16 | 1.01 | 0.92 |
| 3.14t | 0.17 | 1.13 | 1.01 |
Shared Queue Across Workers
Millions of calls/s. Workers each push their share of the keys and wait
at a barrier before draining the shared queue. Each successful push and
pop counts separately. The lock-based heapq baseline uses one shared
threading.Lock. The paged queue uses relaxed pop. The
one-worker row here uses the same lock-based harness and units as the
multi-worker rows.
| Workers | Python | heapq + lock | Concurrent pop |
|---|---|---|---|
| 1 | 3.14t | 0.40 | 1.50 |
| 4 | 3.14t | 0.17 | 4.19 |
| 8 | 3.12 | 0.13 | 0.89 |
| 8 | 3.14t | 0.15 | 5.34 |
Setup and Reproduction
| Item | Configuration |
|---|---|
| Machine | 4 × Intel Xeon E7-8860 v4 at 2.20 GHz (72 cores, 144 hardware threads), 503 GB RAM, Linux 5.15, glibc 2.35 |
| Rust results | b814a0e, rustc 1.100.0, release mode, no target-cpu flags |
| Rust timing | Criterion 0.5.1 medians from one run. The largest cases use 10 samples and a 3-second measurement target. Different groups ran on separate physical cores. The scaling run used eight physical cores on one NUMA node and ran alone. |
| Load | Other users idle (load average 0.0 at the start) |
| Python queue results | Package built from 0989af0. The later commit 267f4c3 contains the benchmark script. Runs were pinned to 32 hardware threads with taskset -c 64-95. |
From the repository, run the Rust harness with the source revision above to reproduce the Rust setup:
cargo bench -p paged-collections-bench --bench sparse
cargo run --release -p paged-collections-bench --bin memory
cargo run --release -p paged-collections-bench --bin churn
cargo run --release -p paged-collections-bench --bin page_sweep
cargo run --release -p paged-collections-bench --bin concurrent_scaling -- 2000000 7
The other Criterion groups are direct, ids, seq and pq. The largest
cases can require tens of GiB. To select a smaller case, pass a Criterion
filter, for example -- /1000/.
Run the Python scripts from the repository root with a release build of
paged-collections installed in the chosen Python environment:
python benchmarks/python/concurrent_scaling.py --n 2000000 --threads 1 2 4 8 --repeat 7
python benchmarks/python/queues.py --n 1000000 --threads 1 2 4 8 --repeat 5
Testing and Soundness
Where unsafe Is Used
| Module | Why |
|---|---|
paged_deque | uninitialized slots in pages; elements are moved in and out manually |
concurrent | atomics publish slots and pages to other threads; guards hand out references to shared slots |
| Python bindings | NumPy views over container memory (guarded by export counts) |
The other single-threaded containers (sparse set and map, direct map,
priority queue, hive, id allocator, page directories) use no unsafe code.
Test Layers
| Layer | What it checks | Where |
|---|---|---|
| Unit and doctests | API contracts, documented examples (including the README) | crates/paged-collections/src, cargo test |
| Model tests (proptest) | random operation sequences against a standard-library oracle (Vec, VecDeque, HashMap, BTreeMap, BinaryHeap) | crates/paged-collections/tests/*_model.rs |
| Panic safety | invariants after panicking Drop, Ord and user closures | unit tests per container |
| Miri | undefined behaviour in the Rust tests, including concurrent tests | Before release, outside CI |
| loom | exhaustive interleavings (preemption bound 2) of the concurrent protocols: publication, free-stack sharding, page installation, guards | src/concurrent/loom_*.rs |
| ThreadSanitizer | data races in the concurrent stress tests | manual |
| Compile-fail doctests | lifetime invariance of every concurrent element type | concurrent module docs |
| Python tests | CPython protocol parity (list, deque, set, dict), batch methods, views, pickling, free threading | tests/ |
Running Them
cargo test --all-features
cargo +nightly miri nextest run -p paged-collections --all-features -E 'not binary(rayon)'
MIRIFLAGS="-Zmiri-tree-borrows -Zmiri-ignore-leaks" cargo +nightly miri nextest run -p paged-collections --all-features --test rayon
MIRIFLAGS="-Zmiri-tree-borrows -Zmiri-ignore-leaks" cargo +nightly miri test -p paged-collections --all-features --doc
RUSTFLAGS="--cfg loom" cargo test -p paged-collections --features concurrent --lib --release loom
cargo build -p paged-collections --no-default-features # no_std
uv sync && uv run pytest
Miri over the full suite is slow. cargo miri nextest run runs tests in
parallel. The rayon tests and doctests run under Tree Borrows because
rayon’s crossbeam-epoch dependency fails the default Stacked Borrows check. The loom suite takes several minutes in release mode.