Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@tolitius
Created February 2, 2012 04:36
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tolitius/1721519 to your computer and use it in GitHub Desktop.
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
Copy link

mfitton commented Aug 16, 2021

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
Copy link
Author

tolitius commented Sep 3, 2021

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