Skip to content

Instantly share code, notes, and snippets.

@souenzzo
Created June 14, 2022 14:25
Show Gist options
  • Save souenzzo/b00220ad5c2b65884f5ab792588be492 to your computer and use it in GitHub Desktop.
Save souenzzo/b00220ad5c2b65884f5ab792588be492 to your computer and use it in GitHub Desktop.
multi dispatch vs map lookup
(defn map-dispatch
[{::keys [ops]} {::keys [op]
:as value}]
(let [impl (get ops op)]
(impl value)))
(def map-dispatch-env
{::ops {::http (fn [{::keys [request]}]
::no-op)}})
(defmulti multi-dispatch ::op)
(defmethod multi-dispatch ::http
[{::keys [request]}]
::no-op)
(let [value {::op ::http
::request {}}
n 1e7
fns {:map-dispatch (partial map-dispatch map-dispatch-env)
:multi-dispatch multi-dispatch}]
(doseq [[ident f] fns]
(dotimes [i 3]
(prn [ident i])
(time
(dotimes [_ n]
(f value))))))
=> #'user/map-dispatch
=> #'user/map-dispatch-env
=> #'user/multi-dispatch
=> #object[clojure.lang.MultiFn 0x225efce "clojure.lang.MultiFn@225efce"]
[:map-dispatch 0]
"Elapsed time: 1735.385917 msecs"
[:map-dispatch 1]
"Elapsed time: 1622.805552 msecs"
[:map-dispatch 2]
"Elapsed time: 1579.659605 msecs"
[:multi-dispatch 0]
"Elapsed time: 1124.112782 msecs"
[:multi-dispatch 1]
"Elapsed time: 1105.441768 msecs"
[:multi-dispatch 2]
"Elapsed time: 1138.197292 msecs"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment