archive2017

Clojure persistent collections: why immutable does not mean slow

How Clojure vectors and maps share structure with 32-way tries, what "effectively O(1)" means, when to use transients, and where you really pay a cost.

7 min read#dev#clojure#lisp

I write Java and Python, and I have been learning Clojure on the side, using Clojure 1.8 (the current stable release; 1.9 is still in alpha). My first worry, coming from Java, was copying: every conj and assoc returns a new collection, so I assumed Clojure copies the whole thing each time. It does not, and I wanted to understand why before I trust it in real code.

This is the first of a few posts about learning Clojure as a Java and Python developer.

The behaviour

user=> (def v1 [1 2 3])
#'user/v1
user=> (def v2 (conj v1 4))
#'user/v2
user=> v1
[1 2 3]
user=> v2
[1 2 3 4]

v1 did not change. In Java you would get this with Collections.unmodifiableList plus a full copy, or with Guava’s ImmutableList and a builder. Both copy everything. Python tuples are the same: t + (4,) builds a new tuple of the full length.

Clojure does something else. The new vector shares almost all of its memory with the old one. This is called structural sharing, and the data structures are called persistent because old versions stay valid after an “update”.

Vectors are 32-way trees

A Clojure vector is a tree. Each internal node has an array of up to 32 children. Each leaf holds up to 32 elements. There is also a separate “tail” array that holds the last up to 32 elements, so that conj at the end is cheap most of the time.

To find element i, the vector takes 5 bits of the index at each level (2^5 = 32) to pick the child. So the depth is about log32(n):

Elements Levels in the tree
up to 32 0 (only the tail)
up to 1,024 1
up to 32,768 2
up to about 1 million 3
up to about 1 billion 5

When you assoc one index, Clojure copies only the nodes on the path from the root to that leaf. That is at most a few arrays of 32 slots. Every other node is shared between the old and the new vector.

You can see the sharing if you poke at the internals. Do not do this in real code; the fields are implementation details. It is only to convince yourself.

user=> (def a (vec (range 100)))
#'user/a
user=> (def b (assoc a 0 :x))
#'user/b
;; leaf 0 was copied, leaf 1 (elements 32-63) is the same object
user=> (identical? (aget (.array (.root a)) 1)
                   (aget (.array (.root b)) 1))
true
user=> (identical? (aget (.array (.root a)) 0)
                   (aget (.array (.root b)) 0))
false

You will get reflection warnings if *warn-on-reflection* is on. That is fine here.

Maps are hash array mapped tries

Small maps, up to 8 entries, are PersistentArrayMap. They are a flat array of keys and values, and a lookup is a linear scan. For 8 entries this is faster than hashing.

user=> (type {:a 1 :b 2})
clojure.lang.PersistentArrayMap
user=> (type (into {} (map vector (range 9) (range 9))))
clojure.lang.PersistentHashMap

Bigger maps become PersistentHashMap, which is a hash array mapped trie (HAMT). The idea comes from Phil Bagwell’s paper “Ideal Hash Trees”. The map takes the 32-bit hash of the key and uses 5 bits at a time to walk down a tree of nodes with up to 32 slots. A node does not allocate 32 slots if it only has 3 children. It keeps a 32-bit bitmap that says which slots are used, and a compact array with only the used ones. Sets are built on top of the same maps.

An assoc on a map copies the path from the root to one node, same as with vectors. A map with a million keys is about 4 levels deep, so an update copies about 4 small arrays.

What “effectively O(1)” means

The Clojure docs say lookups and updates are “O(log32 n)”, and people often call it “effectively constant”. The math is still logarithmic. In practice the tree never gets deeper than about 6 or 7 levels, because you will run out of memory long before you have 32^7 elements. So the cost has a small fixed upper bound.

It is still slower than an ArrayList.get in Java. A Java array lookup is one memory access. A Clojure vector lookup is a few pointer jumps through small arrays. For most business code (parsing JSON, building a response, holding config) this difference does not matter. For tight numeric loops it can matter.

Transients for building a collection in one go

When you build a big collection step by step, each conj copies a path, and the old versions become garbage right away. Nobody else will see the in-between versions, so the copying is wasted work.

Transients fix this. You turn a persistent collection into a transient, change it in place with the ! functions, and turn it back:

(defn build [n]
  (loop [i 0, v []]
    (if (< i n)
      (recur (inc i) (conj v i))
      v)))

(defn build-t [n]
  (loop [i 0, v (transient [])]
    (if (< i n)
      (recur (inc i) (conj! v i))
      (persistent! v))))

transient and persistent! are both O(1). They do not copy the tree. The transient marks nodes that it owns and edits those in place.

On my laptop build-t is clearly faster for a million elements. I am not putting numbers here because a quick (time ...) at the REPL is not a good benchmark (JIT warm-up, GC). If you want real numbers, use the criterium library and run each version many times.

You often do not need to write transients yourself. into, vec, set, frequencies and group-by already use them inside. So (into [] xs) is the normal way, and it is fast.

The transient mistake I made

The ! functions return the collection, and you must use the return value. Do not “bash in place” like a Java HashMap:

;; wrong: ignores the return value of assoc!
user=> (let [t (transient {})]
         (dotimes [i 20] (assoc! t i i))
         (count (persistent! t)))
8

It returns 8, not 20. When the map grows past 8 entries, assoc! returns a new transient hash map, and the code above throws it away. It looks like it works for small inputs, which makes it easy to miss. The right way is to thread the value through loop or reduce:

user=> (count (persistent! (reduce (fn [t i] (assoc! t i i))
                                   (transient {})
                                   (range 20))))
20

Other rules: use a transient only in one place, do not keep it after persistent!, and do not share it between threads.

When you really pay a cost

Persistent collections are fine as a default. These are the cases where I would look closer:

  • Many small updates in a hot loop. Each update allocates a few small arrays. The GC handles short lived garbage well, but it is not free. Use a transient, or reduce with into.
  • Numbers. A normal vector stores boxed objects (java.lang.Long). For a large numeric array, (vector-of :long) stores primitives in the leaves, and a plain Java array (long-array, double-array) is faster still. For heavy number work, arrays and type hints are the honest choice.
  • The wrong collection for the access pattern. nth on a list or a lazy seq walks from the start. last on a vector is also linear because it goes through the seq; use peek for the last element of a vector. count on a lazy seq realizes the whole seq.
  • subvec keeps the whole vector alive. It is O(1) because it is a view on the original. If you take a small subvec from a huge vector and keep it, the huge vector stays in memory. Wrap it in vec (or into []) if you keep it for long.
  • Big keys. A map lookup has to hash the key. Clojure collections cache their hash after the first time, so using a vector or a map as a key is fine, but the first hash of a large nested key walks the whole thing.

How I think about it now

Coming from Java, I expected immutability to be a trade of speed for safety. For the code I write, the speed cost is small and the safety gain is big: I can pass a map to a function and know it will not change under me, and I can keep an old version around for free. When a profiler points at a collection, I will try transients first, then primitive arrays.