Skip to content

Instantly share code, notes, and snippets.

@Hendekagon
Created September 9, 2021 20:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hendekagon/06ee05130c7fc7c7f2f042000ac79224 to your computer and use it in GitHub Desktop.
Save Hendekagon/06ee05130c7fc7c7f2f042000ac79224 to your computer and use it in GitHub Desktop.
Comparison of function dispatch methods performance in Clojure
(require '[criterium.core :as c])
(defprotocol W (w [this x y]))
(def w1 (reify W (w [t x y] (* x y))))
(c/quick-bench (w w1 4 4))
; protocol dispatch
; Execution time mean : 6.625560 ns
(defrecord Wr [w])
(def w2 (Wr. (fn [x y] (* x y))))
(c/quick-bench ((:w w2) 4 4))
; function-in-record dispatch
; Execution time mean : 7.944109 ns
(def w3 {:w (fn [x y] (* x y))})
(c/quick-bench ((:w w3) 4 4))
; function-in-map dispatch
; Execution time mean : 32.106786 ns
(defmulti Wm (fn [kind x y] kind))
(defmethod Wm :w [_ x y] (* x y))
(c/quick-bench (Wm :w 4 4))
; multimethod dispatch
; Execution time mean : 44.309771 ns
; protocols are fastest, records around the same, functions in maps and multimethods slowest
; trade off is performance vs flexibility as protocols and functions-in-records can only dispatch
; on type or keyword, whereas functions-in-maps and multimethods can dispatch on vectors or anything
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment