Sub topic 10
Transients and batch updates
This chapter assumes you know path copying and structural sharing from the earlier chapters, and that you are comfortable reading Python.
The cost of many small updates
Path copying makes one update cheap. A loop of thousands of updates still allocates a fresh path for each one. Each intermediate version is garbage as soon as the next update replaces it, and nobody ever reads it.
Building a 100,000-element vector by calling append 100,000 times makes 100,000 short-lived path copies. Only the final version matters.
The idea: temporary exclusive ownership
A transient is a temporary, mutable view of a persistent structure. It follows three rules:
- You create it from a persistent value in O(1).
- Inside it, nodes that the transient itself created can be changed in place, because nobody else can see them.
- When you finish, you convert it back to a persistent value and stop using the transient.
Nodes inherited from the original version are still shared, so the transient must copy them the first time it writes to them. Each node is copied at most once per batch. After that, writes to it are in place.
A working sketch
This toy vector has fixed size and one level of chunks. A normal set copies one chunk and the root. The transient tracks ownership by type: a chunk it has copied is a list, and a shared chunk is still a tuple.
W = 4 # chunk width
class Vec:
def __init__(self, chunks):
self.chunks = chunks # tuple of tuples
def get(self, i):
c, j = divmod(i, W)
return self.chunks[c][j]
def set(self, i, v):
c, j = divmod(i, W)
old = self.chunks[c]
chunk = old[:j] + (v,) + old[j + 1:]
return Vec(self.chunks[:c] + (chunk,) + self.chunks[c + 1:])
def transient(self):
return TVec(list(self.chunks))
class TVec:
def __init__(self, chunks):
self.chunks = chunks
self.copies = 0
def set(self, i, v):
if self.chunks is None:
raise RuntimeError("transient already frozen")
c, j = divmod(i, W)
if not isinstance(self.chunks[c], list): # still shared
self.chunks[c] = list(self.chunks[c])
self.copies += 1
self.chunks[c][j] = v
return self
def persistent(self):
frozen = tuple(c if isinstance(c, tuple) else tuple(c)
for c in self.chunks)
self.chunks = None # invalidate the transient
return Vec(frozen)
base = Vec(tuple(tuple(range(k, k + W)) for k in range(0, 16, W)))
t = base.transient()
for i in range(W):
t.set(i, 99) # four writes, all in chunk 0
v2 = t.persistent()
assert t.copies == 1 # chunk 0 was copied once
assert base.get(0) == 0 # old version unchanged
assert v2.get(0) == 99
assert v2.chunks[1] is base.chunks[1] # untouched chunks still sharedFour ordinary set calls would have built four roots and four chunks. The transient built one chunk. This sketch's persistent() still walks the root, which costs O(chunks). Real implementations flip an ownership flag instead, so the conversion is O(1).
How real libraries do it
Real libraries track ownership with an edit token stored in each node. A node whose token matches the transient's token can be mutated. Any other node is copied and stamped with the token. Freezing invalidates the token.
- Clojure exposes
transient,assoc!,conj!andpersistent!. - Immutable.js offers
withMutations. - Immer takes a different route. It gives you a draft object to mutate, then produces a new immutable value using structural sharing.
Common errors
- Reusing a transient after
persistent!. The nodes now belong to the frozen value, so a further write could change a published version. Good libraries throw, as the sketch does. - Ignoring the return value. In Clojure the transient operations may return a different object, so you must use
(assoc! t k v)'s result. Don't rely on the original reference being updated. - Sharing a transient across threads. It has no synchronization. It is a local tool for one thread.
- Using it for a single update. With one write, a transient only adds overhead.
Exercise
Exercise
A loop applies 1,000 updates to a persistent vector whose writes all land in the same leaf chunk. Compare the number of leaf chunks copied with ordinary persistent updates and with a transient.
Show answer
Ordinary updates copy that leaf on every write, so about 1,000 leaf copies (plus the path above it each time). A transient copies the leaf once, on the first write, then mutates its own copy in place for the remaining 999 writes.