man ocaml/hashtbl

How OCaml's Hashtbl and polymorphic hash work

lib / OCaml 10 mindraft

checked against: OCaml 5.5.2

What happens when you put a key into an OCaml Hashtbl, and how can a table with a few thousand entries take seconds to fill?

let counts = Hashtbl.create 16 in
List.iter
  (fun word ->
    match Hashtbl.find_opt counts word with
    | Some c -> Hashtbl.replace counts word (c + 1)
    | None -> Hashtbl.add counts word 1)
  words

Hashtbl works for keys of any type without asking you for a hash function or an equality. Both come from the runtime, and both look at the key’s memory representation. This article reads stdlib/hashtbl.ml and runtime/hash.c at OCaml 5.5.2 and checks what they say with small programs compiled with ocamlopt 5.5.2 (no flambda) on an Apple M2 Pro.

The short version

A table is a record with an array of buckets. Each bucket is a linked list of mutable cells. The array length is a power of two, at least 16, and it doubles when the table holds more than twice as many bindings as there are buckets. A key’s bucket is its hash ANDed with the array length minus one. The hash is caml_hash, a C function based on MurmurHash3 that walks the key breadth-first and stops after 10 “meaningful” values. Keys in a bucket are compared with polymorphic compare. Unless you ask for randomization, the hash seed is 0, so the layout is the same on every run.

The data structure

The type is short (hashtbl.ml L21-L32):

type ('a, 'b) t =
  { mutable size: int;                        (* number of entries *)
    mutable data: ('a, 'b) bucketlist array;  (* the buckets *)
    seed: int;                        (* for randomization *)
    mutable initial_size: int;                (* initial array size *)
  }

and ('a, 'b) bucketlist =
    Empty
  | Cons of { mutable key: 'a;
              mutable data: 'b;
              mutable next: ('a, 'b) bucketlist }

This is separate chaining. Every binding is its own heap block with a key, a value and a pointer to the next cell.

data (length 16, a power of two)
+---+---+---+---+-- ... --+----+
| E | o | E | o |         | E  |
+---+-|-+---+-|-+-- ... --+----+
      |       |
      v       v
   [k|d|o]  [k|d|E]
        |
        v
     [k|d|E]          E = Empty, o = pointer to a Cons cell

create rounds the requested size up to a power of two, starting from 16 (L68-L78). Asking for less gets you 16 anyway:

$ ./hash_facts
create 0 -> 16 buckets; create 1000 -> 1024 buckets

Adding, and when the array grows

add puts a new cell at the front of its bucket and checks the load (L542-L547):

let add h key data =
  let i = key_index h key in
  let bucket = Cons{key; data; next=h.data.(i)} in
  h.data.(i) <- bucket;
  h.size <- h.size + 1;
  if h.size > Array.length h.data lsl 1 then resize key_index h

Array.length h.data lsl 1 is twice the bucket count, so the table resizes when the load factor goes above 2. With 16 buckets that happens at the 33rd key:

after 32 keys: 16 buckets
after 33 keys: 32 buckets

resize doubles the array and moves every cell into the new one (L145-L154). insert_all_buckets (L117-L143) keeps a tail pointer for each new bucket and appends, so cells that land in the same bucket keep their relative order. When no iteration is running it reuses the existing cells instead of allocating new ones. While iter or fold is running, the table flips the sign of initial_size as a flag, and a resize then copies the cells, so the traversal still walks the old chains.

add never looks for an existing binding. Two adds with the same key leave two cells, and remove takes away only the newest:

length 2, find 2, find_all [2;1]
after remove: find 1

replace is the one that overwrites. It walks the bucket first, and if it finds the key it mutates that cell’s key and data in place (L635-L658). So the counting loop above costs two bucket walks per word, one for find_opt and one for replace. OCaml 5.5 added Hashtbl.find_and_replace, which returns the old value and stores the new one in a single walk.

Equality is polymorphic compare

Inside a bucket, the generic table tests keys with compare key k = 0 (find, L582-L595). That is the runtime’s structural comparison, a call into C that walks both values. find and find_opt unroll the first three cells of the chain before falling back to a recursive loop.

Using compare rather than = has one visible effect. nan = nan is false, but compare nan nan is 0, so a float key of nan can be found again:

Hashtbl.find h nan                   found

The hash function

The generic table hashes with this (L530-L540):

external seeded_hash_param :
  int -> int -> int -> 'a -> int = "caml_hash" [@@noalloc]

let hash x = seeded_hash_param 10 100 0 x
...
let key_index h key =
  if Obj.size (Obj.repr h) >= 4
  then (seeded_hash_param 10 100 h.seed key) land (Array.length h.data - 1)
  else invalid_arg "Hashtbl: unsupported hash table format"

The Obj.size test rejects tables in an older record layout with fewer fields, which the source calls “old hash tables”.

caml_hash in runtime/hash.c L184-L300 takes two limits. count is the number of meaningful values to mix in (10), and limit is the number of values it may put in its work queue (100, capped at HASH_QUEUE_SIZE, 256). It walks the value breadth-first, roughly like this:

queue = [key]
while queue not empty and count > 0:
  v = next in queue
  int          -> mix it in,            count - 1
  string       -> mix all its bytes,    count - 1
  float        -> mix it in,            count - 1
  float array  -> mix each element,     count - 1 per element
  other block  -> mix tag and size (free), enqueue its fields
                  until the queue has held `limit` values
final mix, keep the low 30 bits

The mixing step is MurmurHash3’s 32-bit round (L33-L46), and the result is masked to 30 bits so it is a non-negative OCaml int on both 32-bit and 64-bit platforms (L297-L299).

Ten values, then nothing

A list cell is a block with two fields, so a list of ints feeds the queue one head and one tail at a time. Every head is an int and counts as meaningful; the cells themselves don’t. After ten elements the count reaches 0 and the hash stops. Two lists that differ only in the 11th element hash the same:

let l10 = List.init 10 Fun.id in
let a = l10 @ [100] and b = l10 @ [200] in
Printf.printf "%d %d %b\n" (Hashtbl.hash a) (Hashtbl.hash b) (a = b)
hash (0..9 @ [100]) = 182325193
hash (0..9 @ [200]) = 182325193
a = b: false

Float arrays count each element, so Array.make 20 1.0 and a copy with a different 16th element collide too (205737115 both).

In a table this turns into one bucket holding every key. I inserted n list keys with Hashtbl.replace, once with keys that differ in the first element (i :: [0; ...; 9]) and once with keys that differ only in the 11th ([0; ...; 9] @ [i]), timing with Sys.time:

$ ./collide
early  n= 5000:      1.0 ms, 4096 buckets, longest bucket 7
late   n= 5000:    837.5 ms, 4096 buckets, longest bucket 5000
early  n=10000:      1.7 ms, 8192 buckets, longest bucket 7
late   n=10000:   3303.4 ms, 8192 buckets, longest bucket 10000
early  n=20000:      5.6 ms, 16384 buckets, longest bucket 9
late   n=20000:  13058.4 ms, 16384 buckets, longest bucket 20000

Doubling n quadruples the time. Every replace walks the whole chain, and every step of the walk is a structural comparison of two lists that agree on their first ten elements. 20,000 keys take 13 seconds.

The fix is to hash more of the key. Hashtbl.hash_param takes the two limits, and a functor table can use it:

module LongListTbl = Hashtbl.Make (struct
  type t = int list
  let equal = List.equal Int.equal
  let hash = Hashtbl.hash_param 50 100
end)
late, hash_param 50 100: 9.1 ms, longest bucket 8

Ints are folded to 32 bits

An OCaml int is stored tagged, as 2n + 1. caml_hash_mix_intnat (L56-L72) XORs the high and low 32 bits of that word before mixing, so 32-bit and 64-bit platforms agree on small ints. The price is that large ints collide in a predictable way. 0 is stored as 1; 4,294,967,297 (2³² + 1) is stored as 2³³ + 3, whose high half is 2 and low half is 3, and 2 XOR 3 is 1:

hash 0 = 129913994, hash 4294967297 = 129913994

Randomization is off by default

The seed is the third argument of caml_hash, and create sets it to 0 unless randomization is on (L73-L78). It is on if you pass ~random:true, if the program called Hashtbl.randomize (), or if OCAMLRUNPARAM contains the letter R (L49-L58). The runtime’s own parameter parser skips R with a comment pointing at hashtbl.mli (startup_aux.c L121).

With seed 0 the order of fold and iter is fixed. This program inserts 3, 1, 2, 100 and 17 into a generic table and into a Hashtbl.Make (Int) table, then prints each table’s fold order:

module IntTbl = Hashtbl.Make (Int)

let keys = [ 3; 1; 2; 100; 17 ]

let () =
  let g = Hashtbl.create 16 and t = IntTbl.create 16 in
  List.iter (fun k -> Hashtbl.replace g k (); IntTbl.replace t k ()) keys;
  let order fold tbl =
    String.concat " "
      (List.rev (fold (fun k () acc -> string_of_int k :: acc) tbl []))
  in
  Printf.printf "Hashtbl:        %s\n" (order Hashtbl.fold g);
  Printf.printf "Hashtbl.Make:   %s\n" (order IntTbl.fold t)
$ ./order
Hashtbl:        2 3 1 17 100
Hashtbl.Make:   2 3 1 17 100
$ OCAMLRUNPARAM=R ./order
Hashtbl:        100 1 17 3 2
Hashtbl.Make:   2 3 1 17 100
$ OCAMLRUNPARAM=R ./order
Hashtbl:        2 3 17 1 100
Hashtbl.Make:   2 3 1 17 100

Without R the order is the same on every run, and it is neither insertion order nor sorted. With R the generic table changes order from run to run.

The interface documents this. A non-randomized table enumerates in an order that is reproducible between runs “and even between minor versions of OCaml” (hashtbl.mli L177-L181).

The functor table didn’t move, because Hashtbl.Make ignores all of this. Its create is create ~random:false sz (L512-L524), and its seeded hash throws the seed away. For a randomized typed table, use Hashtbl.MakeSeeded.

The functor doesn’t avoid the C hash

Hashtbl.Make (Int) replaces polymorphic compare with Int.equal, which compiles to a plain integer test. It does not replace the hash. Int.hash is defined in stdlib/int.ml as the same external (int.ml L126-L129):

external seeded_hash_param :
  int -> int -> int -> 'a -> int = "caml_hash" [@@noalloc]
let seeded_hash seed x = seeded_hash_param 10 100 seed x
let hash x = seeded_hash_param 10 100 0 x

In a test that counts 100,000 ints (43,282 distinct) after parsing them, the generic table and the Hashtbl.Make (Int) table took 23.1 ms and 22.5 ms for the whole process, best of 11. Sizing the generic table up front with Hashtbl.create 65536 saved more, 18.6 ms, by skipping the eleven doublings from 16 to 32,768 buckets.

Curious facts

  • Hashtbl.hash "" is 0. The empty string mixes in no bytes and a length of 0, and MurmurHash3’s final mix maps 0 to 0.
  • 0.0 and -0.0 hash the same, and so do all NaNs: caml_hash_mix_double normalises both before mixing (L89-L115).
  • A string counts as one meaningful value no matter how long it is, and all of its bytes are mixed. Hashing a 1 MB string key reads 1 MB.
  • Hashtbl.add on an existing key shadows it, and Hashtbl.length counts both bindings.
  • find and find_opt in the generic table are written out by hand for the first three cells of a chain, then fall back to a loop.

History

  • OCaml 3.01 (9 March 2001) added Hashtbl.replace.
  • OCaml 4.00.0 (26 July 2012) replaced the generic hash with the MurmurHash3-based one, fixed its handling of -0.0 and NaN, and added ~random, Hashtbl.randomize, the R flag in OCAMLRUNPARAM and the MakeSeeded functor, “to randomize collision patterns and improve security” (CVE-2012-0839).
  • OCaml 4.05 added Hashtbl.find_opt.
  • OCaml 5.5.0 (19 June 2026) added Hashtbl.find_and_replace and Hashtbl.find_and_remove.

Sources

ls ocaml/