concept assoc in category clojure

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
foldoperation 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 thefoldoperation 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-inanddissocare fundamental operations on maps (they also work on other Note data structures such as vectors).
assocreplaces 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).assocforsorted-mapis 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-inprofile is different fromassoc, 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
assocon some supported data structures. The benchmark executesassocon 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.
assocbenchmark for different map types.![]()
We can see that
defrecordis an order of magnitude slower than other types. This can be explained remembering thatdefrecordbuilds its associative nature on top of Java class attributes:associs implemented by matching the required key in a condp condition resulting in a linear behavior. Since normal usage ofdefrecordincludes just a few keys, it shouldn’t be a concern for performance.