man erlang/maps

Maps on the BEAM: flatmaps, HAMTs and immutability

lib / Erlang and the BEAM 9 mindraft

checked against: Erlang/OTP 29.1.3

What is an Elixir map, if nothing in it can ever change? Every update returns a new map, and the old one stays valid:

counts = %{apple: 1}
more = Map.update(counts, :apple, 1, &(&1 + 1))
{counts, more}
# {%{apple: 1}, %{apple: 2}}

If that copied the whole map every time, counting a million words would copy a million maps. It doesn’t, and the reason is in two C files of the Erlang runtime, erl_map.h and erl_map.c. Elixir’s Map module is a thin layer over them. This article reads those files at tag OTP-29.1.3 and checks them with small scripts on an Apple M2 Pro running Elixir 1.20.5 on Erlang/OTP 29.1.3 (erts 17.1.2). The map type belongs to the VM, so everything here holds for Erlang code too; I look at it from the Elixir side.

The short version

A map has two shapes. Up to 32 keys it is a flatmap: a tuple of keys in sorted order, followed by an array of values in the same order. A lookup scans the keys one by one. From the 33rd key on it is a HAMT, a hash array mapped trie with 16 branches per level. An update never changes anything in place. In a flatmap it copies the value array and shares the key tuple. In a HAMT it copies only the nodes on the path from the root to the key.

The small shape: flatmap

erl_map.h defines the header of a small map:

typedef struct flatmap_s {
    Eterm thing_word;
    Uint  size;
    Eterm keys;      /* tuple */
} flatmap_t;

The values follow the header directly, and keys points to an ordinary tuple holding the keys. The limit is a constant in the same file:

#ifdef DEBUG
#define MAP_SMALL_MAP_LIMIT    (3)
#else
#define MAP_SMALL_MAP_LIMIT    (32)
#endif

So a map with 32 keys costs 3 header words, 32 value words, and a 33-word key tuple (one word for the tuple’s own header): 68 words. A debug build of the VM switches to the big shape after just 3 keys.

Lookups don’t use the sort order. A pattern like %{^key => value} compiles to a get_map_elements instruction, and with one key the arm64 loader turns it into i_get_map_element (ops.tab), whose code calls get_map_element in beam_common.c. That function walks the key array from the start. When the key is an immediate, such as a small integer or an atom, each step is one word comparison:

if (is_immed(key)) {
    for (i = 0; i < n; i++) {
        if (ks[i] == key) {
            return vs[i];
        }
    }
}

The order matters on insert. erts_maps_put copies the old keys into a new tuple and slides the new key into its place with erts_cmp_flatmap_keys. That function compares atoms by their raw term value, which is their index in the atom table, not by their name. So a small map with atom keys lists them in the order the atoms were created:

# No atom literals: these three atoms come into being here, in this order.
created = Enum.map(~w(zz_late aa_late mm_late), &String.to_atom/1)
inserted = created |> Enum.sort() |> Enum.reverse()
m = Enum.reduce(inserted, %{}, &Map.put(&2, &1, 1))
IO.inspect(created, label: "created ")
IO.inspect(inserted, label: "inserted")
IO.inspect(Map.keys(m), label: "Map.keys")
$ elixir atoms.exs
created : [:zz_late, :aa_late, :mm_late]
inserted: [:zz_late, :mm_late, :aa_late]
Map.keys: [:zz_late, :aa_late, :mm_late]

The script avoids atom literals on purpose. When I first wrote the inserted list as [:zz_late, :mm_late, :aa_late], the atoms already existed by the time String.to_atom ran, and Map.keys came out in the order the literals appear in the source.

Not alphabetical, and not insertion order. inspect prints the same order, because Inspect.Map only sorts when you pass custom_options: [sort_maps: true].

The big shape: a hash trie

The comment at the top of erl_map.c says where the big shape comes from: “hashmaps are an adaption of Rich Hickeys Persistent HashMaps which were an adaption of Phil Bagwells - Hash Array Mapped Tries”.

A key’s 64-bit hash is used 4 bits at a time. hashmap_index(hash) is hash & 0xf, and each level shifts the hash right by 4. A node keeps a 16-bit bitmap of which of its 16 slots are used and stores only those, so erts_hashmap_get finds a slot by counting the set bits below it:

hval = MAP_HEADER_VAL(hdr);
ix   = hashmap_index(hx);
if (hval != 0xffff) {
    bp   = 1 << ix;
    if (!(bp & hval)) {
        /* not occupied */
        return NULL;
    }
    ix = hashmap_bitcount(hval & (bp - 1));
}
node  = ptr[ix+1];

A bitmap of 0xffff marks a full node, which is indexed directly. The leaves are cons cells [Key | Value]. With a 64-bit hash, HAMT_MAX_LEVEL is 64 / 4 = 16 levels. Keys whose hashes agree in all 64 bits end up together in a collision node at the bottom, a plain tuple searched one by one.

root (bitmap 0b0100_1000_0000_0010)
 ├─ slot 1 ─> [k1 | v1]
 ├─ slot 11 ─> node (bitmap ...) ─> [k7 | v7], [k9 | v9], ...
 └─ slot 14 ─> [k4 | v4]

The hash for a map key is erts_map_hash, which in a normal build is erts_internal_hash. For an immediate it mixes the tagged word with two multiplications and three xor-shifts, and no random seed is involved. A small integer’s tagged word is the same in every run, so a big map with integer keys lists them in the same order every time. (An atom’s word depends on its place in the atom table, so atom keys make no such promise.) You can see the switch from one shape to the other by building a map from 32 down to 1 and then adding 33:

small = Enum.reduce(32..1//-1, %{}, fn k, acc -> Map.put(acc, k, k) end)
large = Map.put(small, 33, 33)
$ elixir maps1.exs
32 keys: [1, 2, 3, 4, 5, 6]
33 keys: [18, 4, 12, 19, 29, 13]
words, 32 keys: 68
words, 33 keys: 123

The 32-key map lists its keys sorted, though they went in backwards. One more key and the order is the hash’s. The change happens inside erts_maps_put: when the key is new and the flatmap already has MAP_SMALL_MAP_LIMIT keys, it builds a trie from the old keys and values plus the new pair. It goes back too. hashmap_delete turns the result back into a flatmap once it has 32 keys or fewer, and deleting key 33 from large gives a 68-word map with sorted keys again.

How an update avoids copying the map

For a flatmap, erts_maps_put and erts_maps_update handle an existing key the same way. The comment says it:

/* only allocate for values,
 * assume key-tuple will be intact
 */

They allocate a new header and a new value array, point the new header at the old key tuple, and copy the values with the one that changed. For a HAMT, erts_hashmap_insert_down walks from the root to the key and records each node on the way, and erts_hashmap_insert_up rebuilds just those nodes. Every other subtree is shared between the old map and the new one.

:erts_debug.size/1 counts shared parts of a term once, and :erts_debug.flat_size/1 counts them as often as they appear. So the size of a list holding both maps, minus the old map and the list’s own 4 words, is what the update allocated:

for n <- [32, 1000] do
  m = Map.new(1..n, fn k -> {k, 0} end)
  m2 = Map.put(m, 7, 1)
  new = :erts_debug.size([m, m2]) - :erts_debug.flat_size(m) - 4
  IO.puts("#{n} keys: #{:erts_debug.flat_size(m)} words, the update allocated #{new}")
end
$ elixir maps2.exs
32 keys: 68 words, the update allocated 35
1000 keys: 3712 words, the update allocated 43

35 words is the 3-word header plus 32 values. The 1,000-key map is 3,712 words, and changing one value in it allocated 43. Below 33 keys an update costs the whole value array. Above it, an update costs a few nodes no matter how big the map is.

There is one more shortcut. If the new value is the same term as the old one, both functions return the original map and give back the memory they took:

found_key:
    if(*vs == value) {
        HRelease(p, shp + MAP_HEADER_FLATMAP_SZ + n, shp);
        return map;
    }

:erts_debug.same(m, Map.put(m, :a, 1)) is true for m = %{a: 1, b: 2}, and false once the value differs.

What a counting loop compiles to

A frequency count in Elixir usually looks like Enum.frequencies/1, whose source at v1.20.5 is:

reduce(enumerable, %{}, fn key, acc ->
  case acc do
    %{^key => value} -> %{acc | key => value + 1}
    %{} -> Map.put(acc, key, 1)
  end
end)

I compiled the same case as Upd.freq/2 in a module, upd.ex, and disassembled it. The output below is trimmed to the function’s body:

$ elixirc upd.ex
$ erl -noshell -eval '{beam_file,_,_,_,_,Code} = beam_disasm:file("Elixir.Upd.beam"), [io:format("~p~n",[I]) || {function,freq,2,_,Is} <- Code, I <- Is], halt().'
{test,is_map,{f,13},[{x,0}]}
{get_map_elements,{f,12},{tr,{x,0},{t_map,any,any}},{list,[{x,1},{x,2}]}}
{gc_bif,'+',{f,0},3,[{x,2},{integer,1}],{x,2}}
{put_map_exact,{f,0},{x,0},{x,0},3,{list,[{x,1},{x,2}]}}
return
{label,12}
{put_map_assoc,{f,0},{x,0},{x,0},2,{list,[{x,1},{integer,1}]}}
return

There is no call to Map.put left; it became a put_map_assoc instruction. When the module is loaded, the arm64 loader rewrites put_map_assoc into update_map_assoc and put_map_exact into update_map_exact (ops.tab). With a single key, the JIT’s code for the first calls erts_maps_put and the code for the second calls erts_maps_update (instr_map.cpp). So an existing key costs two searches, one in get_map_elements and one in erts_maps_update. Map.update/4 has the same case with a function call in place of + 1, and Map.get/3 followed by Map.put/3 also searches twice. None of the three saves a lookup.

Curious facts

  • A debug build of the VM caps flatmaps at 3 keys instead of 32 (MAP_SMALL_MAP_LIMIT).
  • In a flatmap, atom keys sort by their index in the atom table. Two maps with the same atom keys can list them in different orders on two VMs that created the atoms in a different order.
  • Deleting from a 33-key map gives you a flatmap back, and so does Map.filter/2 when it leaves 32 keys: both returned a 68-word map with sorted keys.
  • Map.put(m, k, v) with the value already there returns m itself, so :erts_debug.same/2 says true.
  • Lookups in a 32-key map are a linear scan, even though the keys are kept sorted. get_map_element never looks at the order; erts_maps_put does, to put a new key in its place.

History

  • OTP 17.0 introduced maps with a single flat representation: erl_map.c doesn’t exist at tag OTP_R16B03, and at OTP-17.0 it has a map_t and no hashmap code.
  • OTP 18.0 added the HAMT. At tag OTP-18.0, erl_map.c opens with the “adaption of Rich Hickeys Persistent HashMaps” comment, and erl_map.h already sets MAP_SMALL_MAP_LIMIT to 32 (3 in debug builds), the same values as in OTP-29.1.3.
  • Enum.frequencies/1 is marked @doc since: "1.10.0" in Elixir’s enum.ex.

Sources

Erlang/OTP at tag OTP-29.1.3 (the installed releases/29/OTP_VERSION reads 29.1.3):

Elixir at tag v1.20.5:

ls erlang/

  • draft ETS: mutable tables in an immutable languageHow ETS gives Erlang a mutable hash table in Erlang/OTP 29: who owns a table, how update_counter changes a number in place, the linear hash table behind a set, the copies on every read, and what it costs against a map.
  • draft How Erlang sorts: lists:sort, keysort and term orderWhat lists:sort does in Erlang/OTP 29: a merge sort written in Erlang that finds runs, a fixed order between all terms, why sorting tuples costs more than sorting integers, and when keysort wins.