Sub topic 3
What makes a hash good: determinism, uniformity, speed
This chapter assumes you know basic Python, binary and hexadecimal notation, bitwise operators, the modulo operator, and how a dictionary maps keys to values. Earlier chapters defined a hash function and showed why hash tables need one. This chapter covers the three properties that decide whether a non-cryptographic hash is good, and how to test each one.
The three properties
A hash function for a data structure must satisfy three requirements, in this order of priority:
- Determinism. The same input always gives the same output.
- Uniformity. Outputs spread evenly across the possible values, so buckets fill evenly.
- Speed. Computing the hash costs little compared with the work it saves.
Determinism is a correctness requirement. Uniformity and speed are quality requirements, and they trade off against each other. Cryptographic hashes add further properties, covered in later chapters.
Determinism
A hash is deterministic if its output depends only on the input bytes and the function's configuration. If it also depended on the time, a memory address, or a random value, a lookup could hash the key to a different bucket than the insert did. The entry would exist but never be found.
The usual way to break determinism is to hash something that is not part of the value. Hashing an object's memory address means two equal objects hash differently. This is why Python requires that objects that compare equal also have equal hashes.
Determinism has a scope, and the scope matters. Python's built-in hash() for strings is deterministic inside one process but deliberately different between runs:
python3 -c "print(hash('hello'))"
python3 -c "print(hash('hello'))"The two commands usually print different numbers. Python picks a random seed at startup, which defends against hash flooding (a later chapter). The consequences are practical:
- Never store
hash(s)in a file, database, or message and expect another process to reproduce it. - Never use it to pick a shard or partition across machines.
- For anything that must survive a restart or cross a process boundary, use a hash with a fixed, documented definition, such as FNV-1a, CRC32, or SHA-256.
The test for determinism is simple: hash the same value several times, in separate processes if the hash will be persisted, and compare.
def fnv1a_32(data: bytes) -> int:
h = 0x811C9DC5
for byte in data:
h ^= byte
h = (h * 0x01000193) & 0xFFFFFFFF
return h
results = {fnv1a_32(b"hello") for _ in range(1000)}
print(len(results)) # 1: one distinct output for 1000 callsTwo other sources of nondeterminism catch people out:
- Text encoding. A hash takes bytes. The string
"é"is two bytes in UTF-8 and one in Latin-1, so the hashes differ. Fix the encoding and normalization form at the boundary. - Platform differences. Hashing raw memory such as integers or structs can differ by byte order and padding. Serialize explicitly first.
Uniformity
A hash table works well when each of its m buckets holds about n/m entries. A uniform hash makes every bucket equally likely for each key. With a skewed hash, some buckets grow long. Lookups in them scan a long chain or probe many slots, and the O(1) average becomes closer to O(n).
Uniformity is judged on the keys you really have, not on random keys. A hash that is excellent on random bytes can be poor on real data such as sequential IDs, file paths with common prefixes, or timestamps. You test it by hashing a realistic key set and comparing bucket counts with the even split.
A simple measure is the chi-square statistic: the sum over buckets of (observed - expected)² / expected. For a uniform hash with m buckets, the statistic is typically near m - 1, give or take about sqrt(2(m - 1)). A much larger value means the distribution is lumpy.
from collections import Counter
def fnv1a_32(data: bytes) -> int:
h = 0x811C9DC5
for byte in data:
h ^= byte
h = (h * 0x01000193) & 0xFFFFFFFF
return h
def fnv_str(s: str) -> int:
return fnv1a_32(s.encode())
def sum_str(s: str) -> int:
return sum(s.encode())
def chi_square(keys, hash_fn, buckets):
counts = Counter(hash_fn(k) % buckets for k in keys)
expected = len(keys) / buckets
return sum((counts.get(i, 0) - expected) ** 2 / expected
for i in range(buckets))
keys = [f"user{i}" for i in range(10_000)]
print("fnv1a:", round(chi_square(keys, fnv_str, 64)))
print("sum: ", round(chi_square(keys, sum_str, 64)))With 64 buckets, the FNV-1a result is typically within a few tens of 63. The sum hash gives a far larger number. Many keys such as user0 through user9999 have similar character sums, so they pile into a narrow band of buckets and leave others empty.
The bucket count interacts with the hash. Many tables use a power of two for m, so hash % m keeps only the low bits. If a hash has weak low bits, such as one whose output is always even, half the buckets stay empty even when the high bits look random. There are two common remedies: use a prime bucket count, or mix the hash further before reducing it. A good hash makes every output bit depend on every input bit, which is the avalanche effect covered later in this tutorial.
Speed
A hash runs on every insert, lookup, and delete, so its cost is paid constantly. Three things determine it:
- Work per byte. FNV-1a does one XOR and one multiply per byte. Fast hashes such as xxHash or SipHash process several bytes per step.
- Fixed overhead. For short keys, setup and finalization can cost more than the per-byte loop. A hash tuned for large buffers can lose on 8-byte keys.
- Implementation. The same algorithm in interpreted Python runs far slower than in C.
That last point means you must measure rather than guess. In CPython, a pure-Python FNV-1a can be slower than hashlib.sha256, because SHA-256 runs in compiled code:
import hashlib
import timeit
import zlib
def fnv1a_32(data: bytes) -> int:
h = 0x811C9DC5
for byte in data:
h ^= byte
h = (h * 0x01000193) & 0xFFFFFFFF
return h
short = b"user12345"
long = b"x" * 4096
candidates = {
"fnv1a (pure Python)": fnv1a_32,
"crc32 (C)": zlib.crc32,
"sha256 (C)": lambda d: hashlib.sha256(d).digest(),
}
for name, fn in candidates.items():
t_short = timeit.timeit(lambda: fn(short), number=20_000)
t_long = timeit.timeit(lambda: fn(long), number=200)
print(f"{name:22} short: {t_short:.4f}s 4 KB: {t_long:.4f}s")Treat the timings as local data, not general truth. The lesson is about method: compare candidates on your key sizes, on your hardware, in your language.
A fast hash that is not uniform is not a bargain. The sum hash is nearly free to compute, but if it lengthens bucket chains by a factor of ten, the total cost is higher. Judge speed together with uniformity.
How the properties trade off
| Property | Failure looks like | How to test | Typical fix |
|---|---|---|---|
| Determinism | Keys inserted but never found; values differ between runs | Hash the same input repeatedly, across processes | Fix encoding, drop random or address-based inputs, document the seed |
| Uniformity | Long chains, many empty buckets, high chi-square | Hash a realistic key set and count per bucket | Mix bits better, change bucket count, change function |
| Speed | Hashing dominates the profile | Benchmark on real key sizes | Use a faster function or a native implementation |
Stronger guarantees cost more. A cryptographic hash such as SHA-256 is slower than FNV-1a in the same language and unnecessary for an in-memory table. It exists to resist attackers, which a hash table with trusted keys does not need. The final chapter of this tutorial covers when to pay for that protection.
Exercise
A teammate stores hash(user_id_string) from Python's built-in hash() in a database column, and uses it to route requests to one of 8 servers via hash % 8. After a deploy, many users are routed to a different server than before. Which property failed, why, and what would you change?
Show answer
Determinism across processes failed. Python randomizes the string hash seed at each process start, so the same user ID hashes differently after a restart or on another machine. Replace it with a hash that has a fixed definition, such as FNV-1a or SHA-256 over the UTF-8 bytes, and check uniformity of h % 8 on real user IDs. Stored values must be recomputed with the new function.
Exercise
You hash 10,000 keys into 128 buckets and compute a chi-square statistic of about 127 with one function and about 9,000 with another. Which is closer to uniform, and what value would you expect from a perfectly uniform hash?
Show answer
The function with about 127 is close to uniform. A uniform hash gives a statistic near m - 1 = 127, with a spread of roughly sqrt(2 × 127) ≈ 16. A value of 9,000 shows that many keys share a few buckets while others stay empty.