I go through the "Clojure programming" book by Chas Emerick, Brian Carper and Christophe Grand.
At the part about memoization, I noticed significantly decreased time elapsed for the second (and other) calls of function without even using memoization.
Sure, using memoization decreased time by order of magnitude, but I'm interested, if Clojure perform something like memoization internally.
Here is the code:
(defn prime?
[n]
(cond
(== 1 n) false
(== 2 n) true
(even? n) false
:else (->> (range 3 (inc (Math/sqrt n)) 2)
(filter #(zero? (rem n %)))
empty?)))
(def n 123)
(time (prime? n))
(time (prime? n))
(let [m-prime? (memoize prime?)]
(time (m-prime? n))
(time (m-prime? n)))
And the output:
"Elapsed time: 0.235977 msecs"
"Elapsed time: 0.054549 msecs"
"Elapsed time: 0.045127 msecs"
"Elapsed time: 0.003814 msecs"
So, why the second call is almost 5 times faster, than the first one?