memoize

added
1.0

ns
clojure.core

type
function

(memoize f)

Returns a memoized version of a referentially transparent function. The
memoized version of the function keeps a cache of the mapping from arguments
to results and, when calls with the same arguments are repeated often, has
higher performance at the expense of higher memory use.

                ;; First we define a function that presumably have some expensive computation.
user=> (defn myfunc[a] (println "doing some work") (+ a 10))
#'user/myfunc

;; Next we create a memoized version of the function.
user=> (def myfunc-memo (memoize myfunc))
#'user/myfunc-memo


;; The first time we call the function with a particular argument the
;; original function is invoked and the value is returned.  The next
;; time the function is called with the same argument the cached result
;; is returned and the original function is NOT called.

user=> (myfunc-memo 1)
doing some work
11
user=> (myfunc-memo 1)
11
user=> (myfunc-memo 20)
doing some work
30
user=> (myfunc-memo 20)
30

            
                
;; Fibonacci number with recursion.
(defn fib [n]
  (condp = n
    0 1
    1 1
    (+ (fib (dec n)) (fib (- n 2)))))

(time (fib 30))
;; "Elapsed time: 8179.04028 msecs"

;; Fibonacci number with recursion and memoize.
(def m-fib
  (memoize (fn [n]
             (condp = n
               0 1
               1 1
               (+ (m-fib (dec n)) (m-fib (- n 2)))))))

(time (m-fib 30))
;; "Elapsed time: 1.282557 msecs"

            
                ;; It's possible to memoize a function with multiple arguments:
(def times (memoize (fn [x y] (* x y))))

(times 1 2) ; => 2

(times 2 0) ; => 0