man clojure/hash-maps
Persistent maps in Clojure: HAMTs and structural sharing
In Clojure, (assoc m k v) returns a new map and leaves m as it was. If
m holds a million entries, does that copy a million entries?
(def m (zipmap (range 1000000) (repeat 0)))
(def m2 (assoc m 5 1))
[(get m 5) (get m2 5)] ;=> [0 1]
It doesn’t. On my machine that assoc allocated 5 new tree nodes and shared
the other 657,200 with m. This article reads the two map classes in Clojure
1.12.7, PersistentArrayMap and PersistentHashMap, and checks them with
small scripts run with clojure -M on OpenJDK 27.0.1.1 on an Apple M2 Pro.
Every claim below comes from that source, Clojure’s changelog, or one of
those scripts.
The short version
A small map is a PersistentArrayMap: one array of keys and values side by
side, searched from the front. When assoc adds a ninth key it becomes a
PersistentHashMap, which is Phil Bagwell’s hash array mapped trie
(HAMT). The trie takes 5 bits of the key’s 32-bit hash per level, so each
node has up to 32 children. A sparse node stores only the children it has,
plus a 32-bit bitmap saying which ones those are. An update copies the nodes
on the path from the root to the changed entry and points the copies at the
old, unchanged subtrees. The class comment sums it up in four lines
(PersistentHashMap.java L18-L26):
A persistent rendition of Phil Bagwell's Hash Array Mapped Trie
Uses path copying for persistence
HashCollision leaves vs. extended hashing
Small maps are arrays
{} is a PersistentArrayMap. Its only data is final Object[] array,
holding k0, v0, k1, v1, .... A lookup walks the array and compares keys
with Util.equiv, or with == when the key is a keyword
(L315-L333).
Every assoc clones the array, and the class comment warns about it in
these words: “Copies array on every change, so only appropriate for
very_small maps”.
The switch is one constant (L35):
static final int HASHTABLE_THRESHOLD = 16;
It counts array slots, two per entry. assoc of a new key checks
array.length >= HASHTABLE_THRESHOLD and, when it is true, builds a hash map
from the array and adds the key to that
(L247-L267).
So eight entries stay an array, and the ninth makes a trie:
$ clojure -M facts.clj
type {} : clojure.lang.PersistentArrayMap
8 entries: clojure.lang.PersistentArrayMap 9 entries: clojure.lang.PersistentHashMap
(array-map) with 10 pairs: clojure.lang.PersistentArrayMap
9-entry literal: clojure.lang.PersistentHashMap
assoc onto 10-entry array-map: clojure.lang.PersistentHashMap
hash-map then dissoc to 1: clojure.lang.PersistentHashMap
The threshold is checked on growth only. array-map builds whatever size you
ask for, and the next assoc of a new key converts it. Nothing converts back:
a hash map shrunk to one entry with dissoc is still a hash map.
The array keeps insertion order, and the trie doesn’t. That is the first surprise most people meet.
(keys (frequencies [5 3 9 1 7 2])) ;=> (5 3 9 1 7 2)
(keys (frequencies [5 3 9 1 7 2 8 4 6 0])) ;=> (0 7 1 4 6 3 2 9 5 8)
The hash
The trie hashes keys with Util.hasheq, which differs from Java’s
hashCode. For a Long it is
Murmur3.hashLong, which mixes the low and high 32 bits of the number
(Numbers.java L1155-L1161,
Murmur3.java L58-L70):
(hash 1) ;=> 1392991556
(.hashCode 1) ;=> 1
Java’s Long.hashCode of a small number is the number itself; Murmur3
mixes its bits before the trie sees them. The Murmur3 seed is a constant,
private static final int seed = 0
(Murmur3.java L46),
so the order of a map’s keys is the same on every run.
One level: 5 bits and a bitmap
The trie picks a child with 5 bits of the hash, starting from the lowest (L276-L279):
static int mask(int hash, int shift){
return (hash >>> shift) & 0x01f;
}
shift is 0 at the root and grows by 5 per level: 0, 5, 10, up to 30, where
only 2 bits remain. That is 7 levels for a 32-bit hash.
Most nodes are BitmapIndexedNodes. Instead of 32 slots, mostly empty, a
node keeps an int bitmap with one bit per possible child, and a packed
array with one key/value pair per set bit. A pair whose key slot is null
holds a child node instead of a value. Lookup tests the bit, then counts the
set bits below it to find the position in the packed array
(L682-L684,
L767-L779):
public IMapEntry find(int shift, int hash, Object key){
int bit = bitpos(hash, shift);
if((bitmap & bit) == 0)
return null;
int idx = index(bit); // Integer.bitCount(bitmap & (bit - 1))
Object keyOrNull = array[2*idx];
Object valOrNode = array[2*idx+1];
if(keyOrNull == null)
return ((INode) valOrNode).find(shift + 5, hash, key);
if(Util.equiv(key, keyOrNull))
return (IMapEntry) MapEntry.create(keyOrNull, valOrNode);
return null;
}
So a sparse node costs a bit test, one Integer.bitCount and one array read
per level. Here is a 3-key
map. The keys 1, 2 and 3 hash to low 5-bit groups 4, 20 and 19, and those are
the three bits set in the root’s bitmap:
$ clojure -M hamt.clj
root bitmap of a 3-key map: 110000000000000010000
hashes of 1 2 3, low 5 bits: (4 20 19)
When a bitmap node already has 16 of its 32 slots in use and needs a 17th, it becomes an
ArrayNode: a plain INode[32] with no bitmap, where mask is the index
(L715-L729).
A dense node skips the popcount. The change goes back on removal: when a
child of an ArrayNode becomes empty and the node had 8 children or fewer
(count <= 8), without calls pack, which rebuilds a bitmap node
(L425-L439).
Two different keys with the same full 32-bit hash can’t be told apart by
any level, so they go into a HashCollisionNode, a plain array of pairs
that findIndex scans with Util.equiv
(L1200-L1209,
L1005-L1012).
That is the comment’s “HashCollision leaves vs. extended hashing”: once the
32 bits run out, Clojure keeps a list rather than computing more hash bits.
A nil key doesn’t enter the trie at all. The map object has two fields,
hasNull and nullValue, for it
(L137-L149).
A million keys
I walked the trie of a million-key map with reflection. The node classes
are package-private, but scripts run in the unnamed module, so
setAccessible works. The walk is short:
(defn walk [node depth visit]
(visit node depth)
(case (short-name node)
"BitmapIndexedNode" (let [^objects a (field node "array")]
(doseq [i (range 0 (alength a) 2)]
(when (and (nil? (aget a i)) (some? (aget a (inc i))))
(walk (aget a (inc i)) (inc depth) visit))))
"ArrayNode" (doseq [child (field node "array") :when child]
(walk child (inc depth) visit))
nil))
$ clojure -M hamt.clj
1M keys: {:nodes {ArrayNode 29731, BitmapIndexedNode 627474},
:nodes-per-level {1 1, 2 32, 3 1024, 4 32768, 5 608295, 6 14726, 7 359}}
nodes in 1M map: 657205
Levels 2, 3 and 4 have exactly 32, 1,024 and 32,768 nodes, so every node
on levels 1 to 3 is a full ArrayNode. A second walk counted where the
entries themselves sit:
entries by level of the node holding them: {4 36787, 5 933612, 6 28883, 7 718}
So 93% of lookups in this map read 5 nodes, and 718 keys need 7.
Path copying
The persistent assoc copies one node per level and nothing else. Each
node’s assoc asks its child for a new child, and if the child changed,
returns a copy of itself with that one slot replaced
(L692-L737).
The copy is cloneAndSet, an array.clone() plus one store
(L1180-L1184):
root root' new: root', A', B', C', D'
| \ | \ shared: every other child of each
A ... A' (same) node on the path, and everything
| | below them
B B'
... ...
To count it, I collected every node of the old map in an
IdentityHashMap and counted the nodes of the new map that weren’t there:
new nodes after one assoc: 5
new nodes after a second assoc (new key): 5
Five nodes out of 657,205, for both an update and an insert. The old map
still answers (get m 5) with 0, because none of its nodes changed.
An assoc that stores the very same value object copies nothing. The leaf
compares the old and new value with ==, each level returns this when the
child it got back is the same object, and the map returns itself
(if(newroot == root) return this;). On a map holding 0 at key 1 and 1000
at key 9, (identical? m (assoc m 1 0)) is true and
(identical? m (assoc m 9 1000)) is false: the literal 0 is the same
cached Long object, the second 1000 is a new one.
What it costs
Path copying makes every update allocate. Counting a million random ints
below 500,000 with (reduce (fn [m x] (assoc m x (inc (get m x 0)))) {} xs)
allocated 685.9 MB in one warm JVM, measured with
ThreadMXBean.getThreadAllocatedBytes. The built-in frequencies did the
same count with 19.5 MB, because it uses a transient, a version of the map
that may edit its own new nodes in place. That is the subject of the
companion post on transients.
Curious facts
(hash 1)is 1392991556, and(.hashCode 1)is 1. Clojure collections hash withhasheq, Java’sHashMapwithhashCode, so the same keys come out of the two maps in different orders.- A 9-entry map literal is a
PersistentHashMap, but(apply array-map (range 20))is a 10-entryPersistentArrayMap. The threshold is only checked when anassocgrows the array. dissocnever turns a hash map back into an array map. APersistentHashMapwith one entry stays one.- In an array map, keyword keys are compared with
==(L315-L333). A map of a few keywords is a short scan of pointer comparisons. maskhas a commented-out alternative,((hash << shift) >>> 27), which takes the hash’s bits from the top instead of the bottom (L276-L279).
History
- Clojure 1.6 (tagged 2014-03-25): new hash functions for primitives and
collections, exposed as
hasheqandclojure.core/hash..hashCodewas left unchanged. - Clojure 1.10 (tagged 2018-12-17): CLJ-1587, “PersistentArrayMap’s
assoc doesn’t respect HASHTABLE_THRESHOLD”, and CLJ-2297,
“PersistentHashMap leaks memory when keys are removed with
without”. - Clojure 1.12.7 (tagged 2026-11-18): the version read here. Its only change is a security fix to function serialization.
Sources
All Clojure links are at tag clojure-1.12.7.
src/jvm/clojure/lang/PersistentArrayMap.java: class comment and threshold, assoc, indexOf and equalKeysrc/jvm/clojure/lang/PersistentHashMap.java: class comment, hash and assoc, mask, ArrayNode, BitmapIndexedNode and its assoc, find, cloneAndSet, createNode, bitpos- Util.java hasheq, Numbers.java hasheq, Murmur3.java hashLong
- changes.md
(1.6 “Hashing”, 1.10 “Collections”, 1.12.7); tag dates from the GitHub API
for the tags
clojure-1.6.0,clojure-1.10.0andclojure-1.12.7 HashCollisionNode.findIndex: L1005-L1012; the Murmur3 seed: L46
grep -rl /lib/clojure/hash-maps/
ls clojure/
- draft Transients: how Clojure mutates in privateHow Clojure 1.12.7's transient maps edit a persistent hash trie in place without anyone noticing: the edit token on every node, what persistent! really does, the eight-entry trap, the thread check that was removed in 1.7, and what it saves.