man haskell/data-map

Data.Map is a tree: how Haskell's containers work

lib / Haskell 13 mindraft

checked against: containers 0.8, GHC 9.14.1

Most languages reach for a hash table when they need a dictionary. What does Haskell’s Data.Map do instead, and why is every lookup O(log n)?

import qualified Data.Map.Strict as Map

counts :: Map.Map Int Int
counts = Map.fromListWith (+) [(x, 1) | x <- [3, 1, 3, 2, 3]]
-- fromList [(1,1),(2,1),(3,3)]

The short answer is that Data.Map is an immutable binary search tree, kept balanced by subtree sizes. This article reads the implementation in containers 0.8, the version that ships with GHC 9.14.1, and checks it with small programs run on an Apple M2 Pro. Every number below comes from that source, the package changelog, or one of those programs.

The short version

A Map k v is a binary search tree ordered by k. Every node stores its key, its value, its two subtrees, and the number of keys below it. Lookups compare the key at each node on the way down. Inserts build a new path from the root to the changed node and share everything else with the old map. When one subtree gets more than 3 times as big as its sibling, a rotation fixes it. For Int keys there is also Data.IntMap, a Patricia trie that branches on the bits of the key and never rebalances.

The node

This is the whole type (Internal.hs L473-L476):

data Map k a  = Bin {-# UNPACK #-} !Size !k a !(Map k a) !(Map k a)
              | Tip

type Size     = Int

The ! marks a strict field. The size is unpacked into the node as a raw machine integer, the key and both subtrees are strict, and the value is lazy. That last detail is the only difference between Data.Map.Lazy and Data.Map.Strict. Both modules use this one type, and the strict module’s functions force each value before they store it. The module header of Data.Map.Strict says the Functor and Traversable instances are shared with the lazy module, “so if they are used the resulting maps may contain suspended values (thunks)” (Strict.hs L62-L66).

Because every node carries its size, Map.size is O(1) (L539-L547), and the map can find the element at a given position in key order in O(log n) with elemAt (L1499-L1507).

Lookup

A lookup is a plain binary search (L579-L586):

lookup :: Ord k => k -> Map k a -> Maybe a
lookup = go
  where
    go !_ Tip = Nothing
    go k (Bin _ kx x l r) = case compare k kx of
      LT -> go k l
      GT -> go k r
      EQ -> Just x

There is no hashing, so the only thing a key needs is an Ord instance. The cost is one compare per level, and the number of levels grows with log n.

Insert: copy the path, share the rest

A map can’t be changed in place, so insert returns a new one. The lazy insertWith shows the pattern (L866-L881):

insertWith :: Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
insertWith = go
  where
    go :: Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
    go _ !kx x Tip = singleton kx x
    go f !kx x (Bin sy ky y l r) =
        case compare kx ky of
            LT -> balanceL ky y (go f kx x l) r
            GT -> balanceR ky y l (go f kx x r)
            EQ -> Bin sy kx (f x y) l r

Each level allocates one new node that points at one new subtree and one old one. An insert into a tree of depth d allocates about d nodes, and the old map is still there, unchanged, sharing all of its other nodes with the new one:

old map               new map (after inserting 6)

    5                     5'
   / \                   / \
  2   8         ==>     2   8'      2, 1, 3 and 9 are shared:
 / \  / \              / \  / \     the new map points at the
1  3 7   9            1  3 7'  9    same nodes as the old one
                          /
                         6

The EQ case of the lazy version stores f x y without evaluating it. A comment above it says that lazy insertWith “always changes the tree, either adding a new entry or replacing an element with a thunk” (L869-L872). The strict version is the same function with EQ -> let !y' = f x y in Bin sy kx y' l r (Strict/Internal.hs L493-L503).

Balance by weight

balanceL and balanceR keep the tree shallow. The rule is in a long comment next to two constants (L4151-L4186):

delta,ratio :: Int
delta = 3
ratio = 2

A node is balanced when neither subtree holds more than delta times as many keys as the other (with an exception for nodes with at most one key below them). When an insert or delete breaks that, the node is rotated, and ratio decides between a single and a double rotation. This is a weight-balanced tree, or “tree of bounded balance”, and the module header cites three papers for it, by Adams (1993), Nievergelt and Reingold (1973), and Hirai and Yamamoto (2011) (L56-L70).

The comment is unusually frank. It says Adams’ paper is “erroneous” about which parameters work, that “for delta=2 and delta>=5 there does not exist any ratio that would work”, which leaves delta 3 or 4 with ratio 2, and that containers picked 3 because “delta=3 is faster on insert operations, and delta=4 has slightly better deletes”.

How deep does that make a real tree? This program builds maps from pseudo-random keys and from keys inserted one by one in ascending order, the worst case for a naive search tree, and reports how many nodes a lookup visits to find each key:

import qualified Data.IntMap.Internal as IMI
import qualified Data.IntMap.Strict as IntMap
import qualified Data.Map.Internal as MI
import qualified Data.Map.Strict as Map
import System.Environment (getArgs)
import Text.Printf (printf)

-- n pseudo-random keys below 2^31 from a linear congruential generator
keys :: Int -> [Int]
keys n = take n (drop 1 (iterate (\x -> (x * 1103515245 + 12345) `mod` 2147483648) 42))

-- the depth of every key: how many nodes a successful lookup visits
mapDepths :: MI.Map k a -> [Int]
mapDepths = go 1
  where
    go _ MI.Tip = []
    go d (MI.Bin _ _ _ l r) = d : go (d + 1) l ++ go (d + 1) r

intMapDepths :: IMI.IntMap a -> [Int]
intMapDepths = go 1
  where
    go _ IMI.Nil = []
    go d (IMI.Tip _ _) = [d]
    go d (IMI.Bin _ l r) = go (d + 1) l ++ go (d + 1) r

report :: String -> [Int] -> IO ()
report name ds =
  printf "%-22s %7d keys  max depth %2d  mean depth %.1f\n" name (length ds) (maximum ds)
    (fromIntegral (sum ds) / fromIntegral (length ds) :: Double)

main :: IO ()
main = do
  [n] <- map read <$> getArgs
  let ks = keys n
  report "Map, random order" (mapDepths (Map.fromList [(k, ()) | k <- ks]))
  report "Map, ascending order" (mapDepths (foldr (\k m -> Map.insert k () m) Map.empty [n, n - 1 .. 1]))
  report "IntMap" (intMapDepths (IntMap.fromList [(k, ()) | k <- ks]))
$ ghc -O2 depth.hs && ./depth 100000 && ./depth 1000000
Map, random order       100000 keys  max depth 22  mean depth 16.1
Map, ascending order    100000 keys  max depth 22  mean depth 15.7
IntMap                  100000 keys  max depth 23  mean depth 17.9
Map, random order      1000000 keys  max depth 27  mean depth 19.6
Map, ascending order   1000000 keys  max depth 26  mean depth 19.3
IntMap                 1000000 keys  max depth 26  mean depth 21.3

log2 of 100,000 is 16.6, and of 1,000,000 it is 19.9. The average key in the map sits within one level of that, and the deepest about a third deeper. Ascending inserts, which turn an unbalanced search tree into a linked list, give a tree just as shallow as random ones.

fromList builds sorted input in linear time

fromList and fromListWith are a strict left fold of an insert into a “builder” rather than into a map (L3582-L3585, builder L3976-L4018). The builder starts as a stack of finished subtrees. While each new key is greater than the previous one it is pushed onto that stack, equal keys are combined in place, and at the end the stack is linked into one tree, so a sorted list becomes a map in O(n). The first key that is smaller than the one before it turns the builder into an ordinary map, and from then on every element is a normal insert or insertWith. On unsorted input fromListWith does the same work as a fold of insertWith.

IntMap: a trie over the bits

Data.IntMap stores Int keys in a different structure, a big-endian Patricia trie. The header cites Okasaki and Gill’s “Fast Mergeable Integer Maps” (1998) and Morrison’s PATRICIA paper (1968), and says benchmarks show it “(much) faster on insertions and deletions when compared to a generic size-balanced map” (IntMap/Internal.hs L47-L63). The type (L362-L366):

data IntMap a = Bin {-# UNPACK #-} !Prefix
                    !(IntMap a)
                    !(IntMap a)
              | Tip {-# UNPACK #-} !Key a
              | Nil

Keys live only in the leaves (Tip). A Bin holds no key and no size, only a Prefix, which encodes the high-order bits that every key below it shares and one marker bit that says which bit this node splits on. Keys with that bit clear go left, keys with it set go right (note, L369-L395):

keys 1, 4, 5 (binary 001, 100, 101)

            Bin (split on bit 2)
           /                 \
      Tip 1                  Bin (split on bit 0)
      (bit 2 clear)          /                \
                         Tip 4                Tip 5
                         (bit 0 clear)        (bit 0 set)

The shape depends only on which keys are present, never on the order they arrived in, so there is nothing to rebalance. A path can’t be longer than an Int has bits, which is why the documented cost of lookup and insert is O(min(n, W)), W being the word size (L619-L627). In the depth experiment the keys are below 2^31, and the deepest IntMap leaf is 26 levels down at a million keys.

The lookup itself is short:

lookup :: Key -> IntMap a -> Maybe a
lookup !k = go
  where
    go (Bin p l r) | left k p  = go l
                   | otherwise = go r
    go (Tip kx x) | k == kx   = Just x
                  | otherwise = Nothing
    go Nil = Nothing

left k p is a single unsigned comparison of the key with the prefix (IntTreeCommons.hs L87-L89). The lookup doesn’t check on the way down whether the key could be in this subtree at all. It walks to a leaf and compares the key there once.

Both structures turned out about equally deep (the trie slightly deeper), so the IntMap path isn’t shorter. What I measured is that it is cheaper. This program times building each map from n pseudo-random keys with fromListWith (+), then looking every key up again:

import Control.Exception (evaluate)
import qualified Data.IntMap.Strict as IntMap
import qualified Data.Map.Strict as Map
import GHC.Clock (getMonotonicTimeNSec)
import System.Environment (getArgs)
import Text.Printf (printf)

-- n pseudo-random keys below 2^31 from a linear congruential generator
keys :: Int -> [Int]
keys n = take n (drop 1 (iterate (\x -> (x * 1103515245 + 12345) `mod` 2147483648) 42))

timed :: String -> IO a -> IO a
timed label act = do
  t0 <- getMonotonicTimeNSec
  r <- act
  t1 <- getMonotonicTimeNSec
  printf "%-26s %8.1f ms\n" label (fromIntegral (t1 - t0) / 1e6 :: Double)
  return r

main :: IO ()
main = do
  [which, n] <- getArgs
  ks <- evaluate (keys (read n))
  _ <- evaluate (sum ks)
  case which of
    "map" -> do
      m <- timed "Map.Strict build" (evaluate (Map.fromListWith (+) [(k, 1 :: Int) | k <- ks]))
      s <- timed "Map.Strict lookups" (evaluate (sum [Map.findWithDefault 0 k m | k <- ks]))
      print s
    _ -> do
      m <- timed "IntMap.Strict build" (evaluate (IntMap.fromListWith (+) [(k, 1 :: Int) | k <- ks]))
      s <- timed "IntMap.Strict lookups" (evaluate (sum [IntMap.findWithDefault 0 k m | k <- ks]))
      print s

Compiled with ghc -O2, each map type run 7 times per size, keeping the best time per line (measured inside the program):

$ for i in 1 2 3 4 5 6 7; do ./mapbench map 100000; done | grep ms | sort -k3 -n | awk '!seen[$1 $2]++'
Map.Strict lookups             13.2 ms
Map.Strict build               46.7 ms
$ for i in 1 2 3 4 5 6 7; do ./mapbench intmap 100000; done | grep ms | sort -k3 -n | awk '!seen[$1 $2]++'
IntMap.Strict lookups          10.9 ms
IntMap.Strict build            31.9 ms
$ for i in 1 2 3 4 5 6 7; do ./mapbench map 1000000; done | grep ms | sort -k3 -n | awk '!seen[$1 $2]++'
Map.Strict lookups            494.6 ms
Map.Strict build             1139.8 ms
$ for i in 1 2 3 4 5 6 7; do ./mapbench intmap 1000000; done | grep ms | sort -k3 -n | awk '!seen[$1 $2]++'
IntMap.Strict lookups         369.1 ms
IntMap.Strict build            714.9 ms

IntMap took 32 to 37% less time to build the map and 17 to 25% less to look every key up. A whole run with a million keys, key list included, also allocated less (+RTS -s, binary built with -rtsopts):

$ ./mapbench-rts map 1000000 +RTS -s 2>&1 | grep 'allocated in'
   1,171,112,576 bytes allocated in the heap
$ ./mapbench-rts intmap 1000000 +RTS -s 2>&1 | grep 'allocated in'
     858,445,600 bytes allocated in the heap

A Bin has three fields where a Data.Map node has five, and an IntMap insert never rotates. I haven’t measured how much of the gap each of those accounts for.

Curious facts

  • Map.size is O(1) because every node stores its size. IntMap.size is O(n): it walks the whole trie and counts the leaves (IntMap L581-L591).
  • The balance comment in Data.Map calls the parameters in Adams’ original paper “erroneous”, and records that delta 4.5 with ratio 2 does not work either (L4151-L4186).
  • An IntMap node used to store the prefix and the mask bit as two separate Ints, as in Okasaki and Gill’s paper. Since containers 0.8 it stores one Int that encodes both, which “saves one word per Bin” (note, L3812-L3850; the two-field node at v0.7, L355-L358).
  • With negative keys, an IntMap’s root splits on the sign bit and puts the non-negative keys on the left, the one place where left keys are not smaller than right keys (same note as above, L369-L395).
  • Data.Map.Strict’s documentation points Int keys to Data.IntMap.Strict (“much better performance for most operations”) and unordered keys to HashMap from the separate unordered-containers package (Strict.hs L33-L40).

History

  • containers 0.5.0.0 (May 2012, bundled with GHC 7.6.1): Data.Map.Strict, Data.Map.Lazy, Data.IntMap.Strict and Data.IntMap.Lazy replace the apostrophe-suffixed strict functions like insertWith'.
  • containers 0.5.4.0 (January 2014, GHC 7.8.1): fromList runs in linear time when its input is already sorted.
  • containers 0.8 (March 2025): the smaller IntMap node with a single Prefix, faster fromList and fromListWith for Data.Map, and partly inlined balancing for insert and delete. It is the version bundled with GHC 9.14.1 (ghc-pkg list prints containers-0.8).

Sources

ls haskell/