Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
assoc 3-arity vs var-args arity performance comparison, see: https://twitter.com/borkdude/status/1341009566012731392/photo/1
(defn slow-assoc [m & [k v & kvs :as dat]]
(if (empty? dat)
m
(apply slow-assoc (assoc m k v) kvs)))
(defn emit-assoc [ [ksym vsym]]
`(assoc ~ksym ~vsym))
(defmacro fast-assoc [msym & kvsyms]
(let [assocs (map #(emit-assoc %)
(partition 2 kvsyms))]
`(-> ~msym ~@assocs)))
(defn test-assoc [assoc-impl]
(time (dotimes [_ 10000000]
(assoc-impl {} :k1 :v1 :k2 :v2 :k3 :v3))))
(def fast-assoc-macro-wrapper #(fast-assoc {} :k1 :v1 :k2 :v2 :k3 :v3))
(defn test-fast-assoc-fn []
(time (dotimes [_ 10000000]
(fast-assoc-macro-wrapper))))
;; TESTS
(test-assoc assoc)
;; "Elapsed time: 2030.44051 msecs"
;; nil
(test-assoc slow-assoc)
;; "Elapsed time: 5497.855402 msecs"
;; nil
(test-fast-assoc-fn)
;; "Elapsed time: 1079.879993 msecs"
nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment