What is the difference between reduce and reduce-kv?
When to use reduce-kv over reduce or vice versa?
Whenever you're reducing associative collections, you should see a performance improvement when using reduce-kv
due to it not allocating vectors/tuples for the key/value pairs. reduce
will work on collections (and maps treated as collections of key/value tuples), but reduce-kv
will only work on associative structures like maps and vectors.
From the IKVReduce
protocol docstring:
"Protocol for concrete associative types that can reduce themselves via a function of key and val faster than first/next recursion over map entries. Called by clojure.core/reduce-kv, and has same semantics (just different arg order)."
The difference in using them is that you don't need to destructure the key/value in your reducing function:
(reduce (fn [m [k v]]
(assoc m k (str v)))
{}
{:foo 1})
(reduce-kv (fn [m k v]
(assoc m k (str v)))
{}
{:foo 1})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With