concept assoc in category clojure

appears as: ssoc, assoc, assoc
Clojure: The Essential Reference

This is an excerpt from Manning's book Clojure: The Essential Reference.

Immutable and persistent vectors or maps are typically created by functions like conj or assoc. Each chunk during a fold operation could produce one of such persistent data structures. Once produced, the same data structures are combined, again producing ephemeral objects that are never consumed after the fold operation returns (see the diagram of the combine-reduce model in fold to know more).

(def ordered-by-count ; #1
  (sorted-map-by
    #(compare (count %2) (count %1))
    [:a :b] 1 [:a] 2 [:b] 3))

(assoc ordered-by-count [:x] 4) ; #2
;; {[:a :b] 1, [:a] 4}

(dissoc ordered-by-count [:x]) ; #3
;; {[:a :b] 1}

assoc, assoc-in and dissoc are fundamental operations on maps (they also work on other Note data structures such as vectors).

assoc replaces the value of an existing key or inserts a new key if one doesn’t exist:

Many Clojure persistent collections, such as maps and vectors are built on HAMTs (Hash Array Mapped Tries), a shallow bit-mapped tree data structure. Most common operation on HAMTs, like traversing or updating are O(log32N) with "N" the number of items. The only exception is sorted-map which is instead implemented as binary tree (more precisely, a self-adjusting variant called Red-Black tree). assoc for sorted-map is still logarithmic but with a constant factor of 2 instead of 32: in practice, there is small (large maps) or no difference (small maps).

assoc-in profile is different from assoc, because it also has a linear dependency on the length "ks" of the input which dominates the tree traversal. In practice, "ks" normally contains just a few items as it represents the level of nesting of the input.

In the following chart we are going to compare assoc on some supported data structures. The benchmark executes assoc on different map types sizes: 10 keys, 50 keys and 100 keys. The key is selected so it exists in the current structure, replacing the existing value:

Figure 11.3. assoc benchmark for different map types.
34 assoc perf

We can see that defrecord is an order of magnitude slower than other types. This can be explained remembering that defrecord builds its associative nature on top of Java class attributes: assoc is implemented by matching the required key in a condp condition resulting in a linear behavior. Since normal usage of defrecord includes just a few keys, it shouldn’t be a concern for performance.