Back

# Maps and Hash Tables

Lots of programming problems require dealing with data organized as key/value pairs. Maybe the simplest way of representing such data in OCaml is an association list, which is simply a list of pairs of keys and values. For example, you could represent a mapping between the 10 digits and their English names as follows:

``# open Core_kernel;;``
``````# let digit_alist =
[ 0, "zero"; 1, "one"; 2, "two"  ; 3, "three"; 4, "four"
; 5, "five"; 6, "six"; 7, "seven"; 8, "eight"; 9, "nine" ]
;;``````
``````
val digit_alist : (int * string) list =
[(0, "zero"); (1, "one"); (2, "two"); (3, "three"); (4, "four");
(5, "five"); (6, "six"); (7, "seven"); (8, "eight"); (9, "nine")]
``````

We can use functions from the `List.Assoc` module to manipulate this data:

``# List.Assoc.find ~equal:Int.equal digit_alist 6;;``
``- : string option = Some "six"``
``# List.Assoc.find ~equal:Int.equal digit_alist 22;;``
``- : string option = None``
``# List.Assoc.add ~equal:Int.equal digit_alist 0 "zilch";;``
``````
- : (int, string) Base__List.Assoc.t =
[(0, "zilch"); (1, "one"); (2, "two"); (3, "three"); (4, "four");
(5, "five"); (6, "six"); (7, "seven"); (8, "eight"); (9, "nine")]
``````

Association lists are simple and easy to use, but their performance is not ideal, since almost every nontrivial operation on an association list requires a linear-time scan of the list.

In this chapter, we'll talk about two more efficient alternatives to association lists: maps and hash tables. A map is an immutable tree-based data structure where most operations take time logarithmic in the size of the map, whereas a hash table is a mutable data structure where most operations have constant time complexity. We'll describe both of these data structures in detail and provide some advice as to how to choose between them.

# Maps

Let's consider an example of how one might use a map in practice. In Chapter 4, Files Modules And Programs, we showed a module `Counter` for keeping frequency counts on a set of strings. Here's the interface:

``````open Core_kernel

(** A collection of string frequency counts *)
type t

(** The empty set of frequency counts  *)
val empty : t

(** Bump the frequency count for the given string. *)
val touch : t -> string -> t

(** Converts the set of frequency counts to an association list.
Every string in the list will show up at most once, and the
integers will be at least 1. *)
val to_list : t -> (string * int) list``````

The intended behavior here is straightforward. `Counter.empty` represents an empty collection of frequency counts; `touch` increments the frequency count of the specified string by 1; and `to_list` returns the list of nonzero frequencies.

Here's the implementation:

``````open Core_kernel

type t = int String.Map.t

let empty = String.Map.empty

let to_list t = Map.to_alist t

let touch t s =
let count =
match Map.find t s with
| None -> 0
| Some x -> x
in
Map.add t ~key:s ~data:(count + 1)``````

Note that in some places the preceding code refers to `String.Map.t`, and in others `Map.t`. This has to do with the fact that maps are implemented as ordered binary trees, and as such, need a way of comparing keys.

To deal with this, a map, once created, stores the necessary comparison function within the data structure. Thus, operations like `Map.find` or `Map.add` that access the contents of a map or create a new map from an existing one, do so by using the comparison function embedded within the map.

But in order to get a map in the first place, you need to get your hands on the comparison function somehow. For this reason, modules like `String` contain a `Map` submodule that has values like `String.Map.empty` and `String.Map.of_alist` that are specialized to strings, and thus have access to a string comparison function. Such a `Map` submodule is included in every module that satisfies the `Comparable.S` interface from Core.

## Creating Maps with Comparators

The specialized `Map` submodule is convenient, but it's not the only way of creating a `Map.t`. The information required to compare values of a given type is wrapped up in a value called a comparator that can be used to create maps using the `Map` module directly:

``# let digit_map = Map.of_alist_exn digit_alist ~comparator:Int.comparator;;``
``val digit_map : (int, string, Int.comparator_witness) Map.t = <abstr>``
``# Map.find digit_map 3;;``
``- : string option = Some "three"``

The preceding code uses `Map.of_alist_exn`, which creates a map from an association list, throwing an exception if there are duplicate keys in the list.

The comparator is only required for operations that create maps from scratch. Operations that update an existing map simply inherit the comparator of the map they start with:

``# let zilch_map = Map.add digit_map ~key:0 ~data:"zilch";;``
``val zilch_map : (int, string, Int.comparator_witness) Map.t = <abstr>``

The type `Map.t` has three type parameters: one for the key, one for the value, and one to identify the comparator. Indeed, the type `'a Int.Map.t` is just a type alias for ```(int,'a,Int.comparator_witness) Map.t```.

Including the comparator in the type is important because operations that work on multiple maps at the same time often require that the maps share their comparison function. Consider, for example, `Map.symmetric_diff`, which computes the difference between two maps.

``# let left = String.Map.of_alist_exn ["foo",1; "bar",3; "snoo",0];;``
``val left : int String.Map.t = <abstr>``
``# let right = String.Map.of_alist_exn ["foo",0; "snoo",0];;``
``val right : int String.Map.t = <abstr>``
``# Map.symmetric_diff ~data_equal:Int.equal left right |> Sequence.to_list;;``
``````
- : (string, int) Map.Symmetric_diff_element.t list =
[("bar", `Left 3); ("foo", `Unequal (1, 0))]
``````

The type of `Map.symmetric_diff`, which follows, requires that the two maps it compares have the same comparator type. Each comparator has a distinct abstract type, so the type of a comparator identifies the comparator uniquely.

``# Map.symmetric_diff;;``
``````
- : ('k, 'v, 'cmp) Map.t ->
('k, 'v, 'cmp) Map.t ->
data_equal:('v -> 'v -> bool) ->
('k, 'v) Map.Symmetric_diff_element.t Sequence.t
= <fun>
``````

This constraint is important because the algorithm that `Map.symmetric_diff` uses depends for its correctness on the fact that both maps have the same comparator.

We can create a new comparator using the `Comparator.Make` functor, which takes as its input a module containing the type of the object to be compared, sexp converter functions, and a comparison function. The sexp converters are included in the comparator to make it possible for users of the comparator to generate better error messages. Here's an example:

``````# module Reverse = Comparator.Make(struct
type t = string
let sexp_of_t = String.sexp_of_t
let t_of_sexp = String.t_of_sexp
let compare x y = String.compare y x
end);;``````
``````
module Reverse :
sig
type comparator_witness
val comparator : (string, comparator_witness) Comparator.t
end
``````

As you can see in the following code, both `Reverse.comparator_witness` and `String.comparator_witness` can be used to create maps with a key type of `string`:

``# let alist = ["foo", 0; "snoo", 3];;``
``val alist : (string * int) list = [("foo", 0); ("snoo", 3)]``
``# let ord_map = Map.of_alist_exn ~comparator:String.comparator alist;;``
``val ord_map : (string, int, String.comparator_witness) Map.t = <abstr>``
``# let rev_map = Map.of_alist_exn ~comparator:Reverse.comparator alist;;``
``val rev_map : (string, int, Reverse.comparator_witness) Map.t = <abstr>``

`Map.min_elt` returns the key and value for the smallest key in the map, which lets us see that these two maps do indeed use different comparison functions:

``# Map.min_elt ord_map;;``
``- : (string * int) option = Some ("foo", 0)``
``# Map.min_elt rev_map;;``
``- : (string * int) option = Some ("snoo", 3)``

Accordingly, if we try to use `Map.symmetric_diff` on these two maps, we'll get a compile-time error:

``# Map.symmetric_diff ord_map rev_map;;``
``````
Characters 27-34:
Error: This expression has type
(string, int, Reverse.comparator_witness) Map.t
but an expression was expected of type
(string, int, String.comparator_witness) Map.t
Type Reverse.comparator_witness is not compatible with type
String.comparator_witness
``````

## Trees

As we've discussed, maps carry within them the comparator that they were created with. Sometimes, for space efficiency reasons, you want a version of the map data structure that doesn't include the comparator. You can get such a representation with `Map.to_tree`, which returns just the tree underlying the map, without the comparator:

``# let ord_tree = Map.to_tree ord_map;;``
``val ord_tree : (string, int, String.comparator_witness) Map.Tree.t = <abstr>``

Even though a `Map.Tree.t` doesn't physically include a comparator, it does include the comparator in its type. This is what is known as a phantom type, because it reflects something about the logic of the value in question, even though it doesn't correspond to any values directly represented in the underlying physical structure of the value.

Since the comparator isn't included in the tree, we need to provide the comparator explicitly when we, say, search for a key, as shown below:

``# Map.Tree.find ~comparator:String.comparator ord_tree "snoo";;``
``- : int option = Some 3``

The algorithm of `Map.Tree.find` depends on the fact that it's using the same comparator when looking up a value as you were when you stored it. That's the invariant that the phantom type is there to enforce. As you can see in the following example, using the wrong comparator will lead to a type error:

``# Map.Tree.find ~comparator:Reverse.comparator ord_tree "snoo";;``
``````
Characters 45-53:
Error: This expression has type
(string, int, String.comparator_witness) Map.Tree.t
but an expression was expected of type
(string, int, Reverse.comparator_witness) Map.Tree.t
Type String.comparator_witness is not compatible with type
Reverse.comparator_witness
``````

## The Polymorphic Comparator

We don't need to generate specialized comparators for every type we want to build a map on. We can instead use a comparator based on OCaml's built-in polymorphic comparison function, which was discussed in Chapter 3, Lists And Patterns. This comparator is found in the `Comparator.Poly` module, allowing us to write:

``# Map.of_alist_exn ~comparator:Comparator.Poly.comparator digit_alist;;``
``- : (int, string, Comparator.Poly.comparator_witness) Map.t = <abstr>``

Or, equivalently:

``# Map.Poly.of_alist_exn digit_alist;;``
``- : (int, string) Map.Poly.t = <abstr>``

Note that maps based on the polymorphic comparator are not equivalent to those based on the type-specific comparators from the point of view of the type system. Thus, the compiler rejects the following:

``````# Map.symmetric_diff
(Map.Poly.singleton 3 "three")
(Int.Map.singleton  3 "four" )
;;``````
``````
Characters 54-84:
Error: This expression has type
string Int.Map.t = (int, string, Int.comparator_witness) Map.t
but an expression was expected of type
(int, string, Comparator.Poly.comparator_witness) Map.t
Type Int.comparator_witness is not compatible with type
Comparator.Poly.comparator_witness
``````

This is rejected for good reason: there's no guarantee that the comparator associated with a given type will order things in the same way that polymorphic compare does.

## Sets

Sometimes, instead of keeping track of a set of key/value pairs, you just want to keep track of a set of keys. You could representing a set of values by a map whose data type is `unit`. But a more idiomatic (and efficient) solution is to use Core's set type, which is similar in design and spirit to the map type, while having an API better tuned to working with sets and a lower memory footprint. Here's a simple example:

``````# let dedup ~comparator l =
List.fold l ~init:(Set.empty ~comparator) ~f:Set.add
|> Set.to_list
;;``````
``val dedup : comparator:('a, 'b) Comparator.t -> 'a list -> 'a list = <fun>``
``# dedup ~comparator:Int.comparator [8;3;2;3;7;8;10];;``
``- : int list = [2; 3; 7; 8; 10]``

In addition to the operators you would expect to have for maps, sets support the traditional set operations, including union, intersection, and set difference. And, as with maps, we can create sets based on type-specific comparators or on the polymorphic comparator.

## Satisfying the Comparable.S Interface

Core's `Comparable.S` interface includes a lot of useful functionality, including support for working with maps and sets. In particular, `Comparable.S` requires the presence of the `Map` and `Set` submodules, as well as a comparator.

`Comparable.S` is satisfied by most of the types in Core, but the question arises of how to satisfy the comparable interface for a new type that you design. Certainly implementing all of the required functionality from scratch would be an absurd amount of work.

The module `Comparable` contains a number of functors to help you automate this task. The simplest one of these is `Comparable.Make`, which takes as an input any module that satisfies the following interface:

``````module type Comparable = sig
type t
val sexp_of_t : t -> Sexp.t
val t_of_sexp : Sexp.t -> t
val compare : t -> t -> int
end``````

In other words, it expects a type with a comparison function, as well as functions for converting to and from s-expressions. S-expressions are a serialization format used commonly in Core and are required here to enable better error messages. We'll discuss s-expressions more in Chapter 17, Data Serialization With S Expressions, but in the meantime, we'll use the `[@@deriving sexp]` annotation that comes from the `ppx_sexp_conv` syntax extension. This declaration kicks off the automatic generation of s-expression conversion functions for the marked type.

The following example shows how this all fits together, following the same basic pattern for using functors described in Chapter 9, Extending Modules:

``````# module Foo_and_bar : sig
type t = { foo: Int.Set.t; bar: string }
include Comparable.S with type t := t
end = struct
module T = struct
type t = { foo: Int.Set.t; bar: string } [@@deriving sexp]
let compare t1 t2 =
let c = Int.Set.compare t1.foo t2.foo in
if c <> 0 then c else String.compare t1.bar t2.bar
end
include T
include Comparable.Make(T)
end;;``````
``````
module Foo_and_bar :
sig
type t = { foo : Int.Set.t; bar : string; }
val ( >= ) : t -> t -> bool
val ( <= ) : t -> t -> bool
val ( = ) : t -> t -> bool
val ( > ) : t -> t -> bool
val ( < ) : t -> t -> bool
val ( <> ) : t -> t -> bool
val equal : t -> t -> bool
val compare : t -> t -> int
...
module Replace_polymorphic_compare :
sig
val ( >= ) : t -> t -> bool
val ( <= ) : t -> t -> bool
val ( = ) : t -> t -> bool
val ( > ) : t -> t -> bool
...
end
module Map :
sig
...
end
module Set :
sig
...
end
end
``````

We don't include the full response from the toplevel because it is quite lengthy, but `Foo_and_bar` does satisfy `Comparable.S`.

In the preceding code we wrote the comparison function by hand, but this isn't strictly necessary. Core ships with a syntax extension which will create a comparison function from a type definition if you write ```[@@deriving compare]``` after the type defintion. We can rewrite the previous example to use this extension

``````# module Foo_and_bar : sig
type t = { foo: Int.Set.t; bar: string }
include Comparable.S with type t := t
end = struct
module T = struct
type t = { foo: Int.Set.t; bar: string } [@@deriving sexp, compare]
end
include T
include Comparable.Make(T)
end;;``````
``````
module Foo_and_bar :
sig
type t = { foo : Int.Set.t; bar : string; }
val ( >= ) : t -> t -> bool
val ( <= ) : t -> t -> bool
val ( = ) : t -> t -> bool
val ( > ) : t -> t -> bool
...
end
``````

The comparison function we get from ```[@@deriving compare]``` will call out to the comparison functions for its component types. As a result, the `foo` field will be compared using `Int.Set.compare`. This is different, and saner than the structural comparison done by polymorphic compare.

If you want your comparison function that orders things in a particular way, you can always write your own comparison function by hand; but if all you need is a total order suitable for creating maps and sets with, then `[@@deriving compare]` is a good choice.

You can also satisfy the `Comparable.S` interface using polymorphic compare:

``````# module Foo_and_bar : sig
type t = { foo: int; bar: string }
include Comparable.S with type t := t
end = struct
module T = struct
type t = { foo: int; bar: string } [@@deriving sexp]
end
include T
include Comparable.Poly(T)
end;;``````
``````
module Foo_and_bar :
sig
type t = { foo : int; bar : string; }
val ( >= ) : t -> t -> bool
val ( <= ) : t -> t -> bool
val ( = ) : t -> t -> bool
val ( > ) : t -> t -> bool
val ( < ) : t -> t -> bool
val ( <> ) : t -> t -> bool
val equal : t -> t -> bool
val compare : t -> t -> int
...
end
``````

That said, for reasons we discussed earlier, polymorphic compare should be used sparingly.

# Hash Tables

Hash tables are the imperative cousin of maps. We walked over a basic hash table implementation in Chapter 8, Imperative Programming 1, so in this section we'll mostly discuss the pragmatics of Core's `Hashtbl` module. We'll cover this material more briefly than we did with maps because many of the concepts are shared.

Hash tables differ from maps in a few key ways. First, hash tables are mutable, meaning that adding a key/value pair to a hash table modifies the table, rather than creating a new table with the binding added. Second, hash tables generally have better time-complexity than maps, providing constant-time lookup and modifications, as opposed to logarithmic for maps. And finally, just as maps depend on having a comparison function for creating the ordered binary tree that underlies a map, hash tables depend on having a hash function, i.e., a function for converting a key to an integer.

# Time Complexity of Hash Tables

The statement that hash tables provide constant-time access hides some complexities. First of all, any hash table implementation, OCaml's included, needs to resize the table when it gets too full. A resize requires allocating a new backing array for the hash table and copying over all entries, and so it is quite an expensive operation. That means adding a new element to the table is only amortized constant, which is to say, it's constant on average over a long sequence of operations, but some of the individual operations can be quite expensive.

Another hidden cost of hash tables has to do with the hash function you use. If you end up with a pathologically bad hash function that hashes all of your data to the same number, then all of your insertions will hash to the same underlying bucket, meaning you no longer get constant-time access at all. Core's hash table implementation uses binary trees for the hash-buckets, so this case only leads to logarithmic time, rather than linear for a traditional hash table.

The logarithmic behavior of Core's hash tables in the presence of hash collisions also helps protect against some denial-of-service attacks. One well-known type of attack is to send queries to a service with carefully chosen keys to cause many collisions. This, in combination with the linear behavior of most hashtables, can cause the service to become unresponsive due to high CPU load. Core's hash tables would be much less susceptible to such an attack because the amount of degradation would be far less.

When creating a hash table, we need to provide a value of type hashable, which includes among other things the function for hashing the key type. This is analogous to the comparator used for creating maps:

``# let table = Hashtbl.create ~hashable:String.hashable ();;``
``val table : (string, '_a) Hashtbl.t = <abstr>``
``# Hashtbl.set table ~key:"three" ~data:3;;``
``- : unit = ()``
``# Hashtbl.find table "three";;``
``- : int option = Some 3``

The `hashable` value is included as part of the `Hashable.S` interface, which is satisfied by most types in Core. The `Hashable.S` interface also includes a `Table` submodule which provides more convenient creation functions:

``# let table = String.Table.create ();;``
``val table : '_a String.Table.t = <abstr>``

There is also a polymorphic `hashable` value, corresponding to the polymorphic hash function provided by the OCaml runtime, for cases where you don't have a hash function for your specific type:

``# let table = Hashtbl.create ~hashable:Hashtbl.Poly.hashable ();;``
``val table : ('_a, '_b) Hashtbl.t = <abstr>``

Or, equivalently:

``# let table = Hashtbl.Poly.create ();;``
``val table : ('_a, '_b) Hashtbl.t = <abstr>``

Note that, unlike the comparators used with maps and sets, hashables don't show up in the type of a `Hashtbl.t`. That's because hash tables don't have operations that operate on multiple hash tables that depend on those tables having the same hash function, in the way that `Map.symmetric_diff` and `Set.union` depend on their arguments using the same comparison function.

# Collisions with the Polymorphic Hash Function

OCaml's polymorphic hash function works by walking over the data structure it’s given using a breadth-first traversal that is bounded in the number of nodes it’s willing to traverse. By default, that bound is set at 10 "meaningful" nodes.

The bound on the traversal means that the hash function may ignore part of the data structure, and this can lead to pathological cases where every value you store has the same hash value. We'll demonstrate this below, using the function `List.range` to allocate lists of integers of different length:

``# Caml.Hashtbl.hash (List.range 0 9);;``
``- : int = 209331808``
``# Caml.Hashtbl.hash (List.range 0 10);;``
``- : int = 182325193``
``# Caml.Hashtbl.hash (List.range 0 11);;``
``- : int = 182325193``
``# Caml.Hashtbl.hash (List.range 0 100);;``
``- : int = 182325193``

As you can see, the hash function stops after the first 10 elements. The same can happen with any large data structure, including records and arrays. When building hash functions over large custom data structures, it is generally a good idea to write one's own hash function.

## Satisfying the Hashable.S Interface

Most types in Core satisfy the `Hashable.S` interface, but as with the `Comparable.S` interface, the question remains of how one should satisfy this interface when writing a new module. Again, the answer is to use a functor to build the necessary functionality; in this case, `Hashable.Make`, using `[@@deriving hash]` to produce the hash function.

``````# module Foo_and_bar : sig
type t = { foo: int; bar: string }
include Hashable.S with type t := t
end = struct
module T = struct
type t = { foo: int; bar: string } [@@deriving sexp, compare, hash]
end
include T
include Hashable.Make(T)
end;;``````
``````
module Foo_and_bar :
sig
type t = { foo : int; bar : string; }
val hash : t -> int
val compare : t -> t -> int
val hashable : t Hashtbl_intf.Hashable.t
module Table :
sig
type key = t
type ('a, 'b) hashtbl = ('a, 'b) Hashtbl.t
...
end
module Hash_set :
sig
...
end
module Hash_queue :
sig
...
end
end
``````

Note that in order to satisfy hashable, a key needs to provide a comparison function, for equality checking, and s-expression conversion, for generating useful errors.

There is currently no analogue of `comparelib` for autogeneration of hash functions, so you do need to either write the hash function by hand, or use the built-in polymorphic hash function, `Hashtbl.hash`.

# Choosing Between Maps and Hash Tables

Maps and hash tables overlap enough in functionality that it's not always clear when to choose one or the other. Maps, by virtue of being immutable, are generally the default choice in OCaml. OCaml also has good support for imperative programming, though, and when programming in an imperative idiom, hash tables are often the more natural choice.

Programming idioms aside, there are significant performance differences between maps and hash tables. For code that is dominated by updates and lookups, hash tables are a clear performance win, and the win is clearer the larger the amount of data.

The best way of answering a performance question is by running a benchmark, so let's do just that. The following benchmark uses the `core_bench` library, and it compares maps and hash tables under a very simple workload. Here, we're keeping track of a set of 1,000 different integer keys and cycling over the keys and updating the values they contain. Note that we use the `Map.change` and `Hashtbl.change` functions to update the respective data structures:

``````open Core_kernel
open Core_bench

let map_iter ~num_keys ~iterations =
let rec loop i map =
if i <= 0 then ()
else loop (i - 1)
(Map.change map (i mod num_keys) ~f:(fun current ->
Some (1 + Option.value ~default:0 current)))
in
loop iterations Int.Map.empty

let table_iter ~num_keys ~iterations =
let table = Int.Table.create ~size:num_keys () in
let rec loop i =
if i <= 0 then ()
else (
Hashtbl.change table (i mod num_keys) ~f:(fun current ->
Some (1 + Option.value ~default:0 current));
loop (i - 1)
)
in
loop iterations

let tests ~num_keys ~iterations =
let test name f = Bench.Test.create f ~name in
[ test "table" (fun () -> table_iter ~num_keys ~iterations)
; test "map"   (fun () -> map_iter   ~num_keys ~iterations)
]

let () =
tests ~num_keys:1000 ~iterations:100_000
|> Bench.make_command
|> Core.Command.run``````

The results show the hash table version to be around four times faster than the map version:

``````(executable ((name map_vs_hash) (libraries (core_bench))))
``````
``````\$ jbuilder build map_vs_hash.exe
Error: exception Sys_error("jbuild.inc: No such file or directory")
Backtrace:
Raised by primitive operation at file "pervasives.ml", line 389, characters 28-54
Called from file "src/io.ml", line 15, characters 11-31
Called from file "src/jbuild.ml", line 979, characters 22-71
Called from file "src/sexp.ml", line 339, characters 36-48
Called from file "list.ml", line 82, characters 20-23
Called from file "src/import.ml" (inlined), line 68, characters 31-41
Called from file "src/jbuild.ml", line 1005, characters 4-71
Called from file "src/jbuild.ml", line 1009, characters 6-63
Called from file "src/jbuild_load.ml", line 164, characters 33-64
Called from file "src/jbuild_load.ml", line 224, characters 23-44
Called from file "src/jbuild_load.ml", line 234, characters 16-58
Called from file "src/main.ml", line 26, characters 13-56
Called from file "bin/main.ml", line 547, characters 7-29
Called from file "vendor/cmdliner/src/cmdliner_term.ml", line 27, characters 19-24
Called from file "vendor/cmdliner/src/cmdliner.ml", line 106, characters 32-39
Called from file "vendor/cmdliner/src/cmdliner.ml", line 136, characters 18-36
Called from file "vendor/cmdliner/src/cmdliner.ml", line 251, characters 22-48
Called from file "bin/main.ml", line 1176, characters 10-51
\$ ./_build/default/map_vs_hash.exe -ascii -quota 1 -clear-columns time speedup
sh: ./_build/default/map_vs_hash.exe: No such file or directory
``````

We can make the speedup smaller or larger depending on the details of the test; for example, it will vary with the number of distinct keys. But overall, for code that is heavy on sequences of querying and updating a set of key/value pairs, hash tables will significantly outperform maps.

Hash tables are not always the faster choice, though. In particular, maps excel in situations where you need to keep multiple related versions of the data structure in memory at once. That's because maps are immutable, and so operations like `Map.add` that modify a map do so by creating a new map, leaving the original undisturbed. Moreover, the new and old maps share most of their physical structure, so multiple versions can be kept around efficiently.

Here's a benchmark that demonstrates this. In it, we create a list of maps (or hash tables) that are built up by iteratively applying small updates, keeping these copies around. In the map case, this is done by using `Map.change` to update the map. In the hash table implementation, the updates are done using `Hashtbl.change`, but we also need to call `Hashtbl.copy` to take snapshots of the table:

``````open Core_kernel
open Core_bench

let create_maps ~num_keys ~iterations =
let rec loop i map =
if i <= 0 then []
else
let new_map =
Map.change map (i mod num_keys) ~f:(fun current ->
Some (1 + Option.value ~default:0 current))
in
new_map :: loop (i - 1) new_map
in
loop iterations Int.Map.empty

let create_tables ~num_keys ~iterations =
let table = Int.Table.create ~size:num_keys () in
let rec loop i =
if i <= 0 then []
else (
Hashtbl.change table (i mod num_keys) ~f:(fun current ->
Some (1 + Option.value ~default:0 current));
let new_table = Hashtbl.copy table in
new_table :: loop (i - 1)
)
in
loop iterations

let tests ~num_keys ~iterations =
let test name f = Bench.Test.create f ~name in
[ test "table" (fun () -> ignore (create_tables ~num_keys ~iterations))
; test "map"   (fun () -> ignore (create_maps   ~num_keys ~iterations))
]

let () =
tests ~num_keys:50 ~iterations:1000
|> Bench.make_command
|> Core.Command.run``````

Unsurprisingly, maps perform far better than hash tables on this benchmark, in this case by more than a factor of 10:

``````(executable ((name map_vs_hash2) (libraries (core_bench))))
``````
``````\$ jbuilder build map_vs_hash2.exe
Error: exception Sys_error("jbuild.inc: No such file or directory")
Backtrace:
Raised by primitive operation at file "pervasives.ml", line 389, characters 28-54
Called from file "src/io.ml", line 15, characters 11-31
Called from file "src/jbuild.ml", line 979, characters 22-71
Called from file "src/sexp.ml", line 339, characters 36-48
Called from file "list.ml", line 82, characters 20-23
Called from file "src/import.ml" (inlined), line 68, characters 31-41
Called from file "src/jbuild.ml", line 1005, characters 4-71
Called from file "src/jbuild.ml", line 1009, characters 6-63
Called from file "src/jbuild_load.ml", line 164, characters 33-64
Called from file "src/jbuild_load.ml", line 224, characters 23-44
Called from file "src/jbuild_load.ml", line 234, characters 16-58
Called from file "src/main.ml", line 26, characters 13-56
Called from file "bin/main.ml", line 547, characters 7-29
Called from file "vendor/cmdliner/src/cmdliner_term.ml", line 27, characters 19-24
Called from file "vendor/cmdliner/src/cmdliner.ml", line 106, characters 32-39
Called from file "vendor/cmdliner/src/cmdliner.ml", line 136, characters 18-36
Called from file "vendor/cmdliner/src/cmdliner.ml", line 251, characters 22-48
Called from file "bin/main.ml", line 1176, characters 10-51
\$ ./_build/default/map_vs_hash2.exe -ascii -clear-columns time speedup
sh: ./_build/default/map_vs_hash2.exe: No such file or directory
``````

These numbers can be made more extreme by increasing the size of the tables or the length of the list.

As you can see, the relative performance of trees and maps depends a great deal on the details of how they're used, and so whether to choose one data structure or the other will depend on the details of the application.