Sub topic 3
What makes a hash good: determinism, uniformity, speed
This chapter assumes you can read Python, use the modulo operator, and know that a dictionary stores values in buckets. A hash function maps any input to a fixed-size number. Three properties decide whether a hash suits a hash table: determinism, uniformity, and speed.
Determinism
A hash function must return the same output every time for the same input. A hash table stores a key in the bucket its hash selects. If the hash changed between calls, lookups would search the wrong bucket and miss the key.
Determinism is relative to a scope. Python's built-in hash() for strings is randomized per process, so the same string hashes differently after a restart. That is fine inside one running program. It is a bug if you save the values to disk or share them between machines. For stable values, use your own function or hashlib.
import hashlib
def stable_hash(text: str) -> int:
digest = hashlib.sha256(text.encode()).digest()
return int.from_bytes(digest[:4], "big")
print(stable_hash("apple") == stable_hash("apple"))Uniformity
A uniform hash spreads inputs evenly over its output range. With 10,000 keys and 256 buckets, a good hash puts about 39 keys in each bucket. A poor hash piles keys into a few buckets, and lookups degrade from constant time toward a linear scan of the overloaded buckets.
The next program compares two hashes on similar keys. The sum of character codes ignores position and gives similar keys similar totals. FNV-1a mixes every byte into the state.
def sum_hash(data: bytes) -> int:
return sum(data)
def fnv1a_32(data: bytes) -> int:
h = 0x811C9DC5
for byte in data:
h ^= byte
h = (h * 0x01000193) & 0xFFFFFFFF
return h
def load_report(hash_fn, buckets=256, n=10_000):
counts = [0] * buckets
for i in range(n):
counts[hash_fn(f"key{i}".encode()) % buckets] += 1
return counts.count(0), max(counts)
print("sum (empty buckets, fullest):", load_report(sum_hash))
print("fnv1a(empty buckets, fullest):", load_report(fnv1a_32))The sum hash can use at most 37 buckets here. The digits of i add between 0 and 36 to a fixed base, so there are only 37 possible sums. At least 219 buckets stay empty, and the used ones hold hundreds of keys. FNV-1a fills nearly all buckets with loads close to 39.
Speed
A hash table computes a hash on every insert and lookup, so the hash must be cheap. A fast hash costs a few operations per byte. Cryptographic hashes such as SHA-256 do more work per byte, and password hashes are slow on purpose. Slowness is a defect in a hash table and a feature in password storage.
| Property | What goes wrong without it | Symptom |
|---|---|---|
| Determinism | Keys stored in one bucket are searched for in another | Lookups miss existing keys |
| Uniformity | Many keys share a few buckets | Operations slow toward linear time |
| Speed | Hashing dominates the cost of each operation | The table is slower than needed |
Common errors
- Persisting Python's
hash()output and expecting it to match after a restart. - Judging uniformity on random test data when real keys are patterned.
- Using a slow cryptographic hash for a hash table, or a fast hash where an attacker is involved. Later chapters cover that second case.
Exercise
A hash function returns len(key) % 8 as the bucket index. Which of the three properties does it satisfy, and which does it fail?
Show answer
It is deterministic and very fast, since the same key always gives the same length. It fails uniformity. Keys of equal length always collide, and most real keys have similar lengths, so only a few buckets get used.