Welcome! Please see the About page for a little more info on how this works.

0 votes
in Java Interop by

reduce works on Java maps, but reduce-kv does not:

user=> (def clojure-map {1 2 3 4})


user=> (def java-map (java.util.HashMap. {1 2 3 4}))


user=> (reduce (fn [sum [k v]] (+ sum k v)) 0 java-map)
user=> (reduce-kv + 0 clojure-map)
user=> (reduce-kv + 0 java-map)

IllegalArgumentException No implementation of method: :kv-reduce of protocol: #'clojure.core.protocols/IKVReduce found for class: java.util.HashMap clojure.core/-cache-protocol-fn\

It's trivial to destructure arguments in a regular reduce, but there are performance implications. The following example yields a 7x speed up when run with the implementation of reduce-kv for java.util.Map as implemented in this patch:

user=> (def big-clojure-map (into {} (map #(vector % %) (range 10000))))


user=> (def big-java-map (java.util.HashMap. big-clojure-map))
Reflection warning, /tmp/form-init7130245387362554027.clj:1:19 - call to java.util.HashMap ctor can't be resolved.


user=> (defn reduce-sum [m] (reduce (fn [sum [k v]] (+ sum k v)) 0 m))


user=> (defn reduce-sum-kv [m] (reduce-kv (fn [sum k v] (+ sum k v)) 0 m))


user=> (time (dotimes [_ 1000] (reduce-sum big-java-map)))
"Elapsed time: 2624.692113 msecs"
user=> (time (dotimes [_ 1000] (reduce-sum-kv big-java-map)))
"Elapsed time: 376.802454 msecs"

1 Answer

0 votes
Reference: https://clojure.atlassian.net/browse/CLJ-1762 (reported by alex+import)