Split 32-bit keys into 16-bit high/low halves and store each 65,536-element chunk as an Array (<=4096), an 8 KB Bitset (>4096), or RLE Runs.
TL;DR30-second simplified summary▾
At cardinality 4,096, a 16-bit uint16[] array costs 8,192 bytes—matching a 65,536-bit dense bitset (8,192 bytes) for an exact break-even threshold.
P — Why Dense Bitsets & WAH Fail at OLAP Scale.
Dense Bitset vs. Roaring Hybrid Containers
An OLAP engine with 2,000 attribute filters over 32-bit row IDs would burn 2,000 * 512 MB = 1 TB of RAM using dense bitsets. Earlier RLE schemes (WAH/EWAH) compress sparse regions, but must sequentially scan compressed words from offset 0 to test random membership.
R & I — The 4,096 Break-Even Threshold in Python.
Roaring 2-Level 16-Bit Container Index
- Problem
- How should an analytics engine store and intersect sparse and dense 32-bit ID sets?
- Naive Solution
- Use a 512 MB dense bitset or a HashSet<Integer> (32+ bytes/entry).
- Why It Fails
- Dense bitsets waste 512 MB on sparse sets; HashSets suffer pointer-chasing and 16x memory overhead.
- Alternatives
- Roaring Bitmaps (16-bit hybrid containers),Dense 2^32 Bitset,WAH Run-Length Bitmaps
- Engineering Decision
- Use Roaring Bitmaps for O(log C) chunk lookup and SIMD-accelerated container intersections.
- Trade-Offs
- Slightly more complex container promotion/demotion code, but 10-100x better memory and speed.
Why does Roaring switch from an Array Container to a Bitset Container at cardinality 4,096?
Each uint16 takes 2 bytes. At 4,096 items, 4,096 * 2 = 8,192 bytes—identical to a 65,536-bit / 8 = 8,192-byte dense bitset! Below 4,096 items, Array Containers save memory; above 4,096, Bitset Containers use constant 8 KB and enable 64-bit/AVX2 bitwise ops:
class RoaringChunkedSet:
THRESHOLD = 4096
def __init__(self) -> None:
self.chunks = {} # high16 -> sorted list[int] or bytearray(8192)
def add(self, x: int) -> None:
hi, lo = (x >> 16) & 0xFFFF, x & 0xFFFF
c = self.chunks.get(hi)
if c is None:
self.chunks[hi] = [lo]
elif isinstance(c, list):
if lo not in c:
c.append(lo)
if len(c) > self.THRESHOLD:
bs = bytearray(8192)
for v in c:
bs[v >> 3] |= 1 << (v & 7)
self.chunks[hi] = bs
else:
c[lo >> 3] |= 1 << (lo & 7)
M & E — Container-to-Container Intersections.
Adaptive Intersection Dispatch
When intersecting two Roaring Bitmaps: Bitset & Bitset executes 1,024 64-bit ANDs (or 256 AVX2 ops); Array & Bitset probes the 8 KB bitset in O(|Array|); Array & Array uses two-pointer merge or galloping search when sizes differ by >64x.