Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multimethods performance

Tags:

clojure

What's the performance hit of using multi methods? If I have 2 functions with the same name, and the same number of arguments that differ only by the type (list vs. int), is my performance going to suffer much?

In other words, it it better to name my vector adding function: "add-vector" or leave it as "add" or possibly "+"?

(For the sake of simplicity let's ignore the problems I may have re-defining built-in functions like "+").

like image 307
Timothy Baldridge Avatar asked Jun 16 '10 12:06

Timothy Baldridge


2 Answers

There is a performance cost to using multi-methods, but unless absolutely necessary, you should continue to use them if they're the best abstraction.

That said, Clojure 1.2's protocols provide a native-speed alternative to multi-methods for certain use cases, and are particularly suited to cases where one might formerly have used a multi-method with a type-based dispatch.

like image 121
sanityinc Avatar answered Nov 18 '22 18:11

sanityinc


Since Clojure can use arbitrary dispatch functions the additional cost of a multimethod is the cost of the dispatch function + a map lookup.

Or as cemerick put it:

(defmulti can-your-dispatch-do-that?
  (fn [& _]
    (if (= (phase-of-moon) :full)
      :do-this
      :do-that)))
like image 1
kotarak Avatar answered Nov 18 '22 18:11

kotarak