3 ms·
Reduce is actually faster than using loop/recur normally IME. Probably at least in part due to chuncked seqs which map and reduce among other functions can tak
by runevault 17y ago
Reduce is actually faster than using loop/recur normally IME. Probably at least in part due to chuncked seqs which map and reduce among other functions can take advantage of.
Most of the built in clojure functions are better optimized than doing things by hand yourself.
- anonjon 17y agoReduce /IS/ a loop: (from clojure.core) ([f val coll] (let [s (seq coll)] (if s (if (chunked-seq? s) (recur f (.reduce (chunk-first s) f val) (chunk-next s)) (recur f (f val (first s)) (next s))) val))) It follows that I can use chunks in a loop... chunking and looping are not mutually exclusive. It also happens to be the case that reduce is a function call, and (AFAIK) that you can't use transients (like conj!) or make use of unboxed values. This is an issue, as such, one should still loop for best performance.
- swannodette 17y agoIf I'm not mistaken chunking is only supported on some of Clojure's data structures. Reduce is certainly the better option with vectors (and maps?) if you write your own loop/recur you'll simply be duplicating the existing implementation. Also I really can't imagine using loop/recur on anything except for vectors and maps most of the time anyway, so why not just use reduce?