I was looking at clojure.core re-groups:
(defn re-groups [^java.util.regex.Matcher m] (let [gc (. m (groupCount))] (if (zero? gc) (. m (group)) (loop [ret [] c 0] (if (<= c gc) (recur (conj ret (. m (group c))) (inc c)) ret)))))
And I thought it would be “better” to rewrite it as a multimethod:
(defmulti re-groups (fn [^java.util.regex.Matcher m] (.groupCount m))) (defmethod re-groups 0 [m] (.group m)) (defmethod re-groups :default [m] (let [idxs (range (inc (.groupCount m)))] (reduce #(conj %1 (.group m %2)) [] idxs)))
However, comparing the time I was getting to see that rewriting is 4 times slower:
clojure.core: "Elapsed time: 668.029589 msecs" multi-method: "Elapsed time: 2632.672379 msecs"
Is this the natural result of multimethods, or is there something else wrong here?
M smith
source share