Skip to content

Instantly share code, notes, and snippets.

@tolitius
Created February 2, 2012 04:36
Show Gist options
  • Select an option

  • Save tolitius/1721519 to your computer and use it in GitHub Desktop.

Select an option

Save tolitius/1721519 to your computer and use it in GitHub Desktop.
clojure bootcamp: loop/recur vs. reduce vs. recursion
(ns bootcamp.factorial)
(defn fast-factorial [number]
(loop [n number factorial 1]
(if (zero? n)
factorial
(recur (- n 1) (* factorial n)))))
(defn fast-no-loop-factorial
([number] (fast-no-loop-factorial number 1))
([number factorial]
(if (zero? number)
factorial
(recur (- number 1) (* factorial number)))))
(defn recursive-factorial
([number] (recursive-factorial number 1))
([number factorial]
(if (zero? number)
factorial
(recursive-factorial (- number 1) (* factorial number)))))
(defn slow-factorial [number]
(reduce #(* %1 %2) 1 (range 1 (inc number))))
(println (time (fast-factorial 20)))
;"Elapsed time: 0.123 msecs"
;2432902008176640000
(println (time (fast-no-loop-factorial 20)))
;"Elapsed time: 0.125 msecs"
;2432902008176640000
;
(println (time (recursive-factorial 20)))
;"Elapsed time: 0.135 msecs"
;2432902008176640000
(println (time (slow-factorial 20)))
;"Elapsed time: 2.897 msecs"
;2432902008176640000
@mfitton

mfitton commented Aug 16, 2021

Copy link
Copy Markdown

The performance difference is huge! Do you know why reduce is so much slower than the other solutions? It's the solution that I would certainly reach for for this problem.

@tolitius

tolitius commented Sep 3, 2021

Copy link
Copy Markdown
Author

great question :)
it was 10 years ago, things improved quite a bit since then:

dev=> (println (time (slow-factorial 20)))
;; "Elapsed time: 0.04197 msecs"
;; 2432902008176640000
dev=> (println (time (fast-factorial 20)))
;; "Elapsed time: 0.034636 msecs"
;; 2432902008176640000

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment