Created
February 2, 2012 04:36
-
-
Save tolitius/1721519 to your computer and use it in GitHub Desktop.
clojure bootcamp: loop/recur vs. reduce vs. recursion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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 |
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
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.