1

I've just started learning Clojure and trying to understand the difference between 2 approaches which at first sight seem very identical.

(def func0 (delay (do 
                    (println "did some work") 
                    100)))
so.core=> (force my-delay2)
did some work
100
so.core=> (force my-delay2)
100
(defn vanilla-func [] (println "did some work") 100)
(def func1 (memoize vanilla-func))
so.core=> (func1)
did some work
100
so.core=> (func1)
100

Both approaches do some sort of function memoization. What am I missing?

I've tried to find the explanation on https://clojuredocs.org/clojure.core/delay & https://clojuredocs.org/clojure.core/memoize but couldn't.

1 Answer 1

8

delay holds one result and you have to deref to get the result. memoize is an unbound cache, that caches the result depending on the input arguments. E.g.

user=> (def myinc (memoize (fn [x] (println x) (inc x))))
#'user/myinc
user=> (myinc 1)
1
2
user=> (myinc 1)
2

In your (argument-less) example the only difference is that you can use the result directly (no deref needed)

Classic use-cases for delay are things needed later, that would block or delay startup. Or if you want to "hide" top-level defs from the compiler (e.g. they do side-effects).

memoize is a classic cache and is best used if the calculation is expensive and the set of input arguments is not excessive. There are other caching options in the clojure-verse, that allow better configurations (e.g. they are not unbound).

Sign up to request clarification or add additional context in comments.

3 Comments

delay also caches exceptions unlike memoize.
What do you mean by unbound cache?
@Estebangs it has no limit; the items in it have no life-time. If you use above function like (run! myinc (range)) your application will eventually run out of memory.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.