concept conj in category clojure

appears as: conj
Clojure: The Essential Reference

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

(loop [i 0 s []]
  (if (< i 10)
    (recur (inc i) (conj s (* i i)))
    s))
;; [0 1 4 9 16 25 36 49 64 81]
(import 'clojure.lang.PersistentQueue)

(def xform  ; #1
  (comp
    (map dec)
    (drop-while neg?)
    (filter even?)))

(defn queue [& items] ; #2
  (reduce conj (PersistentQueue/EMPTY) items))

(defn maintain ; #3
  ([fx f coll]
    (into (empty coll) (fx f coll)))
  ([xform coll]
    (into (empty coll) xform coll)))

(def input-queue
  (queue -10 -9 -8 -5 -2 0 1 3 4 6 8 9))

(def transformed-queue  ; #4
  (maintain xform input-queue))

(peek transformed-queue) ; #5
;; 0

(into [] transformed-queue) ; #6
;; [0 2 8]

conj delegates the input collection to find the best way to insert a new element. conj implementation for maps and sets (ordered or not) is a very different operation than the one for sequential collections (vectors, lists, ranges and so on), where the item can simply be appended without worrying about the existing content.

The following chart shows a comparison between maps and sets (ordered or unordered). conj has been used in all cases to add a non-existent keys into an increasingly bigger data structure (up to 1 million keys). For sorted collections, the new key has been selected to be roughly in the middle (using integer types) of the existing keys.

Figure 8.3. Efficiency of conj for sets and maps, ordered and unordered.
17 conj time by type

conj is O(log N) for sorted maps and sorted sets. This is remarkable feature for an ordered collection. conj on unsorted maps (or sets) is instead near O(1) constant time (more precisely O(log 32 N) which is irrelevant in most practical cases).

The next chart repeats similar benchmark on some of the most used sequential types. As expected, conj performs faster on these types because there is no need to check on the existence of the element, or to prepare space for the new key-pair in a specific place in the underlying data structure.

Figure 8.4. Efficiency of conj for sequential data structures.
17 conj time by type list

The very fast results on lists and ranges is primarily because conj just creates a cons-cell, a small object that is linked to the rest of the collection. The reader should also keep in mind that conj is not designed for bulk-inserts of many elements (for which other functions like “into” are better suited).