开发者

Multimethods performance

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 muc开发者_JS百科h?

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 "+").


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.


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)))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜