man swift/dictionary
How Swift's Dictionary works: open addressing, SipHash and copy-on-write
Why does a Swift dictionary print its keys in a different order every time
the program runs, and what does var b = a cost when a holds a million
entries?
var counts: [String: Int] = [:]
for word in words {
counts[word, default: 0] += 1
}
for (word, n) in counts {
print(word, n)
}
This article reads the standard library at the swift-6.4.2-RELEASE tag, mostly
stdlib/public/core/HashTable.swift, NativeDictionary.swift,
DictionaryStorage.swift, Hasher.swift and SipHash.swift, and checks
what it says with small programs built with swiftc -O (Apple Swift 6.4.2)
on an Apple M2 Pro. Every number below comes from that source, a Swift
Evolution proposal, or one of those programs.
The short version
A native Dictionary is a struct holding one reference to a storage object.
That object carries a few counters, a bitmap with one bit per slot, an array
of keys and an array of values, all in one allocation. The number of slots
is a power of two, and the table is never more than three quarters full. A
key’s hash picks a starting slot, and a lookup walks forward one slot at a
time until it finds the key or an empty slot. That is open addressing with
linear probing. Hashes come from SipHash-1-3, keyed by 128 random bits chosen when
the process starts and by a per-table seed, the storage object’s address.
Iteration walks the bitmap from slot 0 up, so the order follows the hashes,
and the hashes change with every run and every table.
One allocation, three arrays
The file comment at the top of Dictionary.swift states the design
(L17-L26):
“Native storage is a hash table with open addressing and linear probing”,
the bucket array forms a ring, and it is “implemented as three arrays: Key,
Value, and a bitmap that marks valid entries”. It ends with “Dictionary
does not use tombstones”. The diagram below it
(L31-L57)
comes down to this:
struct Dictionary<K, V> one pointer, 8 bytes
|
v
_DictionaryStorage<K, V> one heap object
+-------------------------------------------+
| isa, refcount |
| _count, _capacity |
| _scale (slots = 2^scale), _age, _seed |
| _rawKeys, _rawValues |
| bitmap: 1 bit per slot, 1 = occupied |
| keys: K K K K K K K K ... (2^scale) |
| values: V V V V V V V V ... (2^scale) |
+-------------------------------------------+
_DictionaryStorage.allocate
(DictionaryStorage.swift L464-L510)
makes this with a single allocWithTailElems_3 call: the bitmap words, then
bucketCount keys, then bucketCount values. Keys and values live in
separate arrays, so a lookup that compares keys never touches the values.
The struct itself is the size of one pointer, as the last lines of
cow.swift (shown in full further down) print:
$ swiftc -O cow.swift -o cow && ./cow
...
MemoryLayout<[Int: Int]>.size = 8
MemoryLayout<[Int]>.size = 8
MemoryLayout<Hasher>.size = 72
An empty dictionary allocates nothing. Every empty native dictionary points at one statically allocated singleton with one slot and a capacity of 0, so that the first insertion allocates real storage (GlobalObjects.cpp L96-L113).
Size and load factor
_HashTable asserts that the slot count is a power of two and keeps
bucketCount - 1 as a mask
(HashTable.swift L32-L41).
The maximum load factor is 3 / 4, and the size for a requested capacity is
the smallest power of two that keeps the table at most three quarters full
and always leaves at least one hole
(L72-L100).
Inserting one key at a time and printing capacity whenever it changes shows
the doubling:
$ swiftc -O growth.swift -o growth && ./growth
empty: capacity 0
count 1: capacity 1
count 2: capacity 3
count 4: capacity 6
count 7: capacity 12
count 13: capacity 24
...
count 12289: capacity 24576
count 24577: capacity 49152
count 49153: capacity 98304
Capacity 49,152 is three quarters of 65,536 slots. Every growth allocates a new storage object and reinserts every entry (NativeDictionary.swift L191-L224).
Finding a key
find is short enough to quote whole
(DictionaryStorage.swift L245-L255):
let hashTable = unsafe _hashTable
var bucket = unsafe hashTable.idealBucket(forHashValue: hashValue)
while unsafe hashTable._isOccupied(bucket) {
if unsafe uncheckedKey(at: bucket) == key {
return (bucket, true)
}
bucket = unsafe hashTable.bucket(wrappedAfter: bucket)
}
return (bucket, false)
idealBucket is hashValue & bucketMask, and bucket(wrappedAfter:) is
(offset + 1) & bucketMask
(HashTable.swift L350-L365).
There is no second hash and no stored hash per entry. Each step checks one
bit in the bitmap and, if it is set, compares one key. When the key is
missing, the slot where the search stopped is exactly where an insert puts
it.
Deleting can’t just clear the bit, because that would cut a probe chain and
hide the keys after it. Instead delete
(L467-L508)
walks the rest of the chain and moves back every entry whose ideal slot lies
between the start of the chain and the hole. That is why the file can say it
uses no tombstones. A comment in Dictionary.swift
(L130-L134)
still has a FIXME about whether to keep “first-come-first-serve” collision
resolution or move to Robin Hood hashing, pointing at a Rust implementation.
The hash: SipHash-1-3 with two seeds
Every lookup hashes the key with the table’s seed
(NativeDictionary.swift L166-L168).
For a 64-bit Int that is Hasher._hash(seed:_:) on its eight bytes
(IntegerTypes.swift.gyb L633-L645),
so even an integer key goes through the full hash function. In
SipHash.swift, compress runs one SipRound per 64-bit word and finalize
runs three
(L78-L95),
which makes it SipHash-1-3. The file’s header comment still says it implements
SipHash-2-4 and SipHash-1-3, but only the 1-3 rounds are left in it.
The key comes from two places. At startup the runtime fills two 64-bit
words from swift_stdlib_random, unless the environment variable
SWIFT_DETERMINISTIC_HASHING is set, in which case both are 0
(GlobalObjects.cpp L143-L161).
Each table then XORs its own _seed into the first word
(SipHash.swift L103-L112).
That per-table seed is the storage object’s address, or in deterministic
mode the table’s scale
(HashTable.swift L108-L132).
The comment there says that without it, some copy operations between two
similar tables would become quadratic. A copy-on-write copy keeps the
seed, “so that we avoid breaking value semantics”.
The same hashValue changes between runs:
$ swiftc -O hashes.swift -o hashes && ./hashes && ./hashes
-8850235302242094718 1731145513896518908
-3463074621963693939 -4372978011573507778
$ SWIFT_DETERMINISTIC_HASHING=1 ./hashes; SWIFT_DETERMINISTIC_HASHING=1 ./hashes
8880661182590738257 691490157317212239
8880661182590738257 691490157317212239
That program is print(42.hashValue, 43.hashValue). The Hasher
documentation says “Do not save or otherwise reuse hash values
across executions of your program”
(Hasher.swift L289-L293).
Why the order changes
Iteration goes through the bitmap word by word, lowest slot first
(HashTable.swift L234-L279).
So the order is the order of hash & mask, and both seeds feed the hash.
This program builds two equal dictionaries the same way, plus a copy of the
first:
var a: [Int: Int] = [:]
var b: [Int: Int] = [:]
for n in 1...10 { a[n] = n * n }
for n in 1...10 { b[n] = n * n }
let c = a // a copy shares a's storage until one of them changes
print("a:", Array(a.keys))
print("b:", Array(b.keys))
print("c:", Array(c.keys))
print("a == b:", a == b)
$ swiftc -O order.swift -o order && ./order && ./order
a: [4, 8, 6, 1, 3, 2, 10, 7, 5, 9]
b: [7, 8, 4, 10, 9, 1, 2, 6, 5, 3]
c: [4, 8, 6, 1, 3, 2, 10, 7, 5, 9]
a == b: true
a: [7, 8, 4, 9, 5, 2, 1, 6, 10, 3]
b: [9, 5, 10, 4, 2, 6, 8, 1, 3, 7]
c: [7, 8, 4, 9, 5, 2, 1, 6, 10, 3]
a == b: true
$ SWIFT_DETERMINISTIC_HASHING=1 ./order
a: [4, 2, 6, 3, 8, 5, 9, 1, 10, 7]
b: [4, 2, 6, 3, 8, 5, 9, 1, 10, 7]
c: [4, 2, 6, 3, 8, 5, 9, 1, 10, 7]
a == b: true
a and b are equal and still list their keys differently in the same
process, because their storage sits at different addresses. c shares a’s
storage, so it lists the same order. With the variable set, all three agree
and the order is the same in every run. The documentation promises only that
the order “is stable between mutations but is otherwise unpredictable”
(Dictionary.swift L331-L334).
In deterministic mode the per-table seed becomes the scale, so the order
still depends on the table’s size. Here b reserves room for 1,000 entries
before the same ten insertions:
var a: [Int: Int] = [:]
var b: [Int: Int] = [:]
b.reserveCapacity(1_000)
for n in 1...10 { a[n] = n * n }
for n in 1...10 { b[n] = n * n }
print("a:", Array(a.keys))
print("b:", Array(b.keys))
$ swiftc -O order2.swift -o order2 && SWIFT_DETERMINISTIC_HASHING=1 ./order2
a: [4, 2, 6, 3, 8, 5, 9, 1, 10, 7]
b: [10, 7, 5, 8, 2, 4, 3, 9, 6, 1]
A second run printed the same two lines.
Copy-on-write
Dictionary is a value type, and var b = a copies only the reference.
Every mutating path calls ensureUnique
(NativeDictionary.swift L257-L277),
which checks whether the storage is uniquely referenced. If it is and there
is room, nothing happens. If it is shared, copy()
(L237-L255)
allocates new storage with the same scale and seed, copies the bitmap, and
copies every entry into the same slot, with no rehashing. Timing it on a
million entries:
var big: [Int: Int] = [:]
for n in 0..<1_000_000 { big[n] = n }
let clock = ContinuousClock()
var copy = big
let t1 = clock.measure { copy = big }
let t2 = clock.measure { copy[0] = -1 } // first write: copies all entries
let t3 = clock.measure { copy[1] = -1 } // copy is unique now
print("assign:", t1, " first write:", t2, " second write:", t3)
print(big[0]!, copy[0]!)
print("MemoryLayout<[Int: Int]>.size =", MemoryLayout<[Int: Int]>.size)
print("MemoryLayout<[Int]>.size =", MemoryLayout<[Int]>.size)
print("MemoryLayout<Hasher>.size =", MemoryLayout<Hasher>.size)
$ swiftc -O cow.swift -o cow && ./cow
assign: 3.75e-07 seconds first write: 0.004649417 seconds second write: 4.875e-06 seconds
0 -1
MemoryLayout<[Int: Int]>.size = 8
MemoryLayout<[Int]>.size = 8
MemoryLayout<Hasher>.size = 72
The assignment takes well under a microsecond, the first write about 4.6 ms,
and the second a few microseconds. Array documents the same scheme: copies
“share the same storage until you modify one of the copies”
(Array.swift L218-L223).
A loop that mutates a dictionary while another variable still holds the
original pays for one full copy on its first write and none after it.
The default subscript
The default: subscript in counts[word, default: 0] += 1 has a _modify
accessor
(Dictionary.swift L938-L957).
It calls mutatingFind once, which makes the storage unique and leaves room
for one more entry
(NativeDictionary.swift L539-L562).
If the key is missing it inserts the default in the slot find stopped at,
then yields the address of the value so += 1 changes it in place. The
older pattern, if let c = counts[w] { counts[w] = c + 1 } else { ... },
hashes and probes once for the read and again for the write.
Building from pairs
Dictionary(_:uniquingKeysWith:) sizes its table from the sequence’s
underestimatedCount before inserting anything
(Dictionary.swift L519-L527).
When the pairs repeat keys, that is far more than needed:
let words = (0..<100_000).map { "w\($0 % 1_000)" }
var loop: [String: Int] = [:]
for w in words { loop[w, default: 0] += 1 }
let eager = Dictionary(words.map { ($0, 1) }, uniquingKeysWith: +)
var merged: [String: Int] = [:]
merged.merge(words.lazy.map { ($0, 1) }, uniquingKeysWith: +)
print("keys:", loop.count)
print("default: loop capacity", loop.capacity)
print("init(_:uniquingKeysWith:) capacity", eager.capacity)
print("merge(_:uniquingKeysWith:) capacity", merged.capacity)
$ swiftc -O presize.swift -o presize && ./presize
keys: 1000
default: loop capacity 1536
init(_:uniquingKeysWith:) capacity 196608
merge(_:uniquingKeysWith:) capacity 1536
A thousand keys end up in 262,144 slots. merge into an empty dictionary
grows as it goes and stops at 2,048 slots.
Curious facts
Hasheris 72 bytes._Statehas eight 64-bit fields, and four of them,v4tov7, are commented “reserved for future use. They aren’t currently used” (SipHash.swift L26-L45). The other 8 bytes are a tail buffer. SE-0206 described the Swift 4.2Hasheras having “320 bits of state”.- The SipHash state starts from the ASCII bytes of
“somepseudorandomlygeneratedbytes”, as the comment above
v0tov3says. - Two equal dictionaries in the same process can iterate in different orders, because each table’s seed is its own address.
- A dictionary of one entry has two slots: capacity 1 is the largest count that leaves a hole at a load factor of three quarters.
- In deterministic mode,
HashTable.swiftadmits that “some operations that merge two similar-sized hash tables will still be quadratic” (L119-L124).
History
- Swift 4.0: SE-0165 adds
init(_:uniquingKeysWith:),merge(_:uniquingKeysWith:),init(grouping:by:),mapValuesand thedefault:subscript. SE-0154 giveskeysandvaluestheir own collection types. - Swift 4.2: SE-0206 introduces
Hasherandhash(into:), with a random per-execution seed thatSWIFT_DETERMINISTIC_HASHING=1turns off. The 4.2 sources carry both a SipHash-1-3 and a SipHash-2-4 core. - Swift 5.0: the hash table is rewritten around the
_HashTablestruct (HashTable.swiftexists at the 5.0 tag and not at 4.2), and per-instance seeds are switched on. The commit that enabled them (September 2018) says that merging two similar-sized sets or dictionaries had been quadratic.
Sources
stdlib/public/core/HashTable.swiftat swift-6.4.2-RELEASE: power-of-two mask, load factor and scale, per-table seed, iterator, ideal bucket and wrap, deletestdlib/public/core/Dictionary.swift: design comment, Robin Hood FIXME, order documentation, init(_:uniquingKeysWith:), default subscriptstdlib/public/core/NativeDictionary.swift: hashValue(for:), resize, copy and ensureUnique, mutatingFindstdlib/public/core/DictionaryStorage.swift: find, allocateSipHash.swift,Hasher.swift,IntegerTypes.swift.gyb,Array.swiftstdlib/public/stubs/GlobalObjects.cpp: empty singleton, hashing parameters- Swift Evolution: SE-0154, SE-0165, SE-0206
- Swift 4.2 sources:
SipHash.swift; per-instance seeds commit 08e0ad66e3
grep -rl /lib/swift/dictionary/
ls swift/
- draft How Swift sortsWhat sort(by:) does in Swift 6.4.2: a Timsort without galloping, insertion sort below 64 elements, a buffer of half the array, a stability guarantee that was true for four years before the documentation said so, and a descending input that costs more than a random one.