man zig/hashmap
Zig's HashMap: metadata bytes, tombstones and a fixed seed
Why does a Zig AutoHashMap list its keys in the same order on every run?
And why can a map that never holds
more than 1,000 keys get 160 times slower at reporting a missing key after a
few thousand removals?
var counts: std.AutoHashMapUnmanaged(u32, u32) = .empty;
defer counts.deinit(gpa);
for (words) |w| {
const slot = try counts.getOrPut(gpa, w);
if (!slot.found_existing) slot.value_ptr.* = 0;
slot.value_ptr.* += 1;
}
This article reads lib/std/hash_map.zig and lib/std/array_hash_map.zig at
the 0.17.1 tag. Zig’s repository now lives on Codeberg; the GitHub mirror
stops at 0.15.2. I checked that the files at the tag are byte for byte the
ones Homebrew installed, and ran small programs built with
zig build-exe -O fast on an Apple M2 Pro. Every number below comes from
that source, the release notes, or one of those programs.
The short version
std.AutoHashMap(K, V) is an open-addressing table with linear probing. Next
to the keys and values it keeps one metadata byte per slot. One bit says
whether the slot holds a key, and the other seven hold the top seven bits of
that key’s 64-bit hash. A lookup compares keys only where those seven bits
match. The table grows when it is 80% full, to the next power of two.
Removing a key leaves a tombstone. The hash for integer keys is Wyhash with a
seed of 0, the same in every process, so the order is the same in every
process too.
A type made by a function
AutoHashMap is a function that runs at compile time and returns a type
(hash_map.zig L46-L48):
pub fn AutoHashMap(comptime K: type, comptime V: type) type {
return HashMap(K, V, AutoContext(K), default_max_load_percentage);
}
default_max_load_percentage is 80
(L118).
AutoContext(K) is another generated struct with a hash and an eql
function. The hash comes from getAutoHashFn
(L11-L34).
When the key type has a unique representation, as integers do, it hashes the
key’s raw bytes in one call, Wyhash.hash(0, std.mem.asBytes(&key)). For
other types it feeds the fields to a streaming Wyhash one at a time. It
refuses []const u8 keys at compile time with a message pointing to
StringHashMap, because hashing a slice’s pointer or its contents would both
be reasonable guesses.
HashMap wraps HashMapUnmanaged and adds two fields, an Allocator and
the context. The unmanaged map is the real table, and its whole state is
three fields
(L522-L538):
a pointer to the metadata, the size, and available, a countdown of how
many more keys fit before the next grow. A fourth field, pointer_stability,
only has a size in safe builds:
$ zig build-exe -O fast sizes.zig && ./sizes
AutoHashMap(u32, u32): 32 bytes, AutoHashMapUnmanaged(u32, u32): 16 bytes
$ zig build-exe sizes.zig && ./sizes
AutoHashMap(u32, u32): 40 bytes, AutoHashMapUnmanaged(u32, u32): 24 bytes
The second build is a debug build, the default.
Sizes and capacities are u32
(L552),
which keeps the struct small and caps the map at about four billion slots.
One allocation
allocate
(L1462-L1494)
asks the allocator for one block and lays it out like this:
header metadata keys values
+-----------------+-----------------+-------------------+-------------------+
| values, keys, | 1 byte per slot | capacity x K | capacity x V |
| capacity | | | |
+-----------------+-----------------+-------------------+-------------------+
^
the map's pointer points here
The map stores a pointer to the first metadata byte, and the header sits
just before it. For u32 keys and values, 65,536 slots take 65,536 × 9
bytes plus the header, about 590 KB.
The metadata byte
The comment on Metadata
(L574-L630)
explains the design. The low bits of the hash choose the slot, and seven
more bits, “the highest ones from a 64 bit hash”, tell keys apart without
reading the keys array. It is a packed struct of a u7 fingerprint and a
u1 used flag, so a byte means one of three things:
0000_0000 free: never used, ends a search
0000_0001 tombstone: a key was removed here, a search goes on
1fff_ffff used: f = top 7 bits of the key's hash
There is no separate tombstone bit. A tombstone is the byte with the used bit clear and the fingerprint set to 1. I printed the metadata of a map after inserting 50, 10, 40, 20 and 30, and again after removing 40:
$ zig build-exe -O fast hm.zig && ./hm
capacity after 5 puts: 8
metadata bytes: 00 ff 00 fa f5 e5 00 a1
after remove(40): 00 ff 00 fa f5 01 00 a1
Five used slots, each with the high bit set, three free ones, and the
removed key’s e5 turned into 01.
A lookup
getIndex
(L968-L1000)
is the whole search:
- Hash the key. The first slot is
hash & (capacity - 1), the low bits. - Take the fingerprint,
hash >> 57. - While the slot’s byte is not free, check it. If it is used and its fingerprint matches, compare the keys and return on a match. Then step to the next slot, wrapping at the end.
- Stop at a free byte, or after
capacityslots.
The last condition matters later. A key that isn’t there ends its search at
the first free byte, so the number of free bytes decides how long a miss
takes. getOrPutAssumeCapacityAdapted
(L1145-L1200)
runs the same loop, remembers the first tombstone it passes, and puts a new
key there instead of in the free slot that ended the search.
Growing
available starts at 80% of the capacity, drops by one for every new key,
and when it would go below zero, growIfNeeded calls grow with
capacityForSize(load + 1)
(L737-L741):
the size times 100/80, plus one, rounded up to a power of two. The first
table has 8 slots (minimal_capacity,
L542).
grow
(L1430-L1460)
allocates the new table, reinserts every used slot, and frees the old one.
Inserting 43,282 distinct keys and printing each new capacity with the key
count that caused it:
$ zig build-exe -O fast ahm.zig && ./ahm
capacities: 8@1 16@7 32@13 64@26 128@52 256@103 512@205 1024@410 2048@820
4096@1639 8192@3277 16384@6554 32768@13108 65536@26215
8 × 80% is 6.4, which rounds down to 6 available slots, so the seventh key doubles the table. That is 14 allocations for 43,282 keys, and the final table is 66% full.
Tombstones
removeByIndex
(L1229-L1235)
writes a tombstone and adds one to available. The doc comment on remove
still asks “does this increase the unused capacity by one?” as a TODO; the
code says yes. So tombstones never count toward the 80%, and a map whose size
stays constant never grows and never cleans them up. A new key reuses the
first tombstone on its path, but a key inserted into a free slot turns that
slot into a used one, and removing it later leaves a tombstone where a free
byte used to be.
I kept 1,000 keys in a map, then repeatedly inserted a new key and removed the oldest one. Every 2,000 rounds I counted the three kinds of metadata byte and timed 100,000 lookups of keys that are not in the map:
start: cap=2048 free=1048 used=1000 tomb=0 miss=9 ns
after 2000 churn ops: cap=2048 free=160 used=1000 tomb=888 miss=40 ns
after 4000 churn ops: cap=2048 free=28 used=1000 tomb=1020 miss=90 ns
after 6000 churn ops: cap=2048 free=3 used=1000 tomb=1045 miss=358 ns
after 8000 churn ops: cap=2048 free=1 used=1000 tomb=1047 miss=761 ns
after 10000 churn ops: cap=2048 free=0 used=1000 tomb=1048 miss=1606 ns
after rehash: cap=2048 free=1048 used=1000 tomb=0 miss=10 ns
The map held 1,000 keys the whole time. After 10,000 rounds there was no
free byte left, so every miss walked all 2,048 slots until limit ran out,
at 1.6 µs per lookup against 9 ns at the start. rehash()
(L1352)
rebuilds the table in place and brings it back. The 0.14.0 release notes,
which added rehash, say it plainly. “Unordered hash maps currently have
a nasty flaw: removals cause HashMaps to become slow.” They also promise the
method will be “unceremoniously deleted” once that is fixed. It is still
there in 0.17.1.
Wyhash with seed 0
Wyhash.hash
(wyhash.zig L178-L196)
takes a short path for inputs of 16 bytes or fewer. For a 4-byte key,
smallKey
(L106-L121)
builds two 64-bit words by repeating the key, and final2 mixes them with
two 64 × 64 → 128-bit multiplications (mum,
L137-L141).
The seed is the constant 0, so the hash of a key, and with it the slot and
the iteration order, depends only on the key and the table size. I ran the
same program twice:
$ ./hm | head -2; ./hm | head -2
AutoHashMap order: 50 10 30 40 20
array_hash_map order: 50 10 40 20 30
AutoHashMap order: 50 10 30 40 20
array_hash_map order: 50 10 40 20 30
The AutoHashMap order is the slot order, which is neither the insertion
order nor sorted, but it is the same every time. The flip side is that
anyone who knows the keys can compute where they land. A map that takes keys
from untrusted input can be fed keys that all collide, and nothing in
AutoContext varies the seed to prevent it.
The array hash map
std.array_hash_map.Auto(K, V) is the other design. Its entries live in a
MultiArrayList
(array_hash_map.zig L130),
so keys and values are two dense arrays in insertion order, and keys() and
values() return them as slices. A small map is searched with a linear scan.
The index is only built once the entry array’s capacity exceeds
linear_scan_max
(L155-L158),
one cache line’s worth of keys. On the M2, with a 128-byte cache line and
4-byte keys, that is 32. The experiment agreed:
index allocated at 33 entries, entries capacity 33
The index is an array of (entry index, distance from home slot) pairs that
is kept at most 60% full
(L1625-L1632),
using u8, u16 or u32 entries depending on its size. An insert that
meets an entry closer to its home slot than the new one takes that slot and
pushes the old entry along, “to keep the max distance_from_start_index as
small as possible”
(L1337-L1345).
The same distance lets a lookup stop early. Removal is swapRemove or
orderedRemove, and there are no tombstones, which is why the 0.14.0 notes
say “array hash maps do not have this flaw.”
The trap is in sorting. The map has sort and sortUnstable. sort calls
MultiArrayList.sort, which calls std.mem.sortContext
(multi_array_list.zig L613),
and that function is an insertion sort
(mem.zig L689-L693):
/// TODO: currently this just calls `insertionSortContext`. The block sort implementation
/// in this file needs to be adapted to use the sort context.
pub fn sortContext(a: usize, b: usize, context: anytype) void {
std.sort.insertionContext(a, b, context);
}
Sorting maps of random u32 values by value:
$ zig build-exe -O fast ahsort.zig && ./ahsort
1000 entries sort 997 us
1000 entries sortUnstable 35 us
10000 entries sort 93491 us
10000 entries sortUnstable 356 us
40000 entries sort 1513304 us
40000 entries sortUnstable 1460 us
Ten times the entries cost 94 times as long with sort, which is what a
quadratic sort does. At
40,000 entries the stable sort takes 1.5 s, a thousand times the unstable
one.
Curious facts
std.AutoHashMapUnmanaged(u32, u32)is 16 bytes in a-O fastbuild and 24 in a debug build. The extra 8 bytes arepointer_stability, a lock thatlockPointerstakes, so that a safe build trips an assertion if the map is changed in a way that would move entries while it is held.- A lookup in a table with no free byte left still terminates, because the
probe loop also counts down from
capacity. In the churn experiment that limit is what every miss ran into. - The unordered map hashes to
u64; the array map’sAutoContextreturns au32, the same Wyhash result truncated (L2224-L2237). array_hash_map.Autostores each key’s hash next to the entry only when comparing keys is expensive.autoEqlIsCheap(L2249-L2265) says yes for integers, floats, pointers, enums and a few others, so au32map stores no hashes.- Calling
std.AutoHashMap(u32, u32)twice gives one and the same type.std.AutoHashMap(u32, u32) == std.AutoHashMap(u32, u32)printedtruein the same experiment that printed the sizes.
History
- 0.14.0 (2025-03-05):
std.hash_mapgainsrehash, with the “nasty flaw” note quoted above. - 0.15.1 (2025-08-19):
std.ArrayListbecomes the unmanaged list; the release notes give the reason as “Having an extra field is more complicated than not having an extra field, so not having it is the null hypothesis.” - 0.16.0 (2026-04-13):
ArrayHashMap,AutoArrayHashMapandStringArrayHashMapare removed, andAutoArrayHashMapUnmanagedbecomesarray_hash_map.Auto. The notes say “the variant without the allocator field is more versatile and the other one should be removed.” The managedAutoHashMapremains in 0.17.1. - 0.17.0 (2026-10-01): “ArrayHashMap.setKey no longer recomputes the entire index.”
Dates are from ziglang.org’s download index.
Sources
- Zig at tag 0.17.1,
lib/std/hash_map.zig: getAutoHashFn L11-L34, AutoHashMap L46-L48, default_max_load_percentage L118, HashMapUnmanaged doc and fields L495-L552, Metadata L574-L630, capacityForSize L737-L741, getIndex L968-L1000, getOrPutAssumeCapacityAdapted L1145-L1200, removeByIndex and remove L1229-L1247, load and growIfNeeded L1288-L1300, rehash L1352, grow and allocate L1430-L1494 lib/std/hash/wyhash.zig: smallKey L106-L121, mum L137-L141, hash L178-L196lib/std/array_hash_map.zig: Auto L15-L17, DataList L130, linear_scan_max L155-L158, sort and sortUnstable L927-L967, insert L1337-L1345, index_capacities L1625-L1632, getAutoHashFn L2224-L2237, autoEqlIsCheap L2249-L2265- multi_array_list.zig L589-L615, mem.zig L689-L693, sort.zig insertionContext L42-L52
- Release notes: 0.14.0, 0.15.1, 0.16.0, 0.17.0; release dates from the download index
grep -rl /lib/zig/hashmap/
ls zig/
- draft Allocators in Zig: who owns the memoryWhat a std.mem.Allocator is in Zig 0.17.1, which allocator main gets in each build mode, how the page, arena, smp, C and new SafeAllocator differ inside, and what each one costs, measured.