Clojure implements and encourages immutability starting from its design principles. However, Clojure is a pragmatic language that allows mutability and side-effects when necessary. Clojure approach to mutability is still elegant and mostly functional. In this chapter we are going to see functions and data structures that mainly exist for their mutable or side-effecting nature. Other parts of Clojure are amenable to mutability and have been described in their respective chapters (for example, concurrency or Java interoperability). Let’s get started with transients.
A transient is a mutable state available to some Clojure data structures and also a function with the same name. Currently supported collections are: vectors, maps and sets.
Transients exist to solve an optimization problem. When large persistent data structures are created or transformed, individual processing steps are subject to immutability overhead, even when clients of the collection are just interested in the final output. Transients offer a way to turn immutability off while the collection is still processing. During transient state the collection: