Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clojure future vs delay

I have been reading through Programming in Clojure and found thing text

(defn get-document [id]
; ... do some work to retrieve the identified document's metadata ... {:url "http://www.mozilla.org/about/manifesto.en.html"
:title "The Mozilla Manifesto"
:mime "text/html"
:content (delay (slurp "http://www.mozilla.org/about/manifesto.en.html"))})

if callers are likely to always require that data, the change of replacing future over delay can prove to be a significant improvement in throughput.

I didn't got this part completely, can someone please explain a bit.

like image 240
rohit Avatar asked Dec 24 '22 22:12

rohit


2 Answers

Simple answer future is background execution of body, delay is on-demand execution of body. Example: if you have list of 100 delay-ed code, and trying to loop through it - code will block while evaluating each list item (e.g. doing HTTP request) and first iteration will be slow. Same with future-d code - it'll evaluate all content in background thread(s) and results will be available instantly in your loop.

Rule of thumb - if there is good chance that some or most of content will not be needed at all - use delay, otherwise use future.

https://clojuredocs.org/clojure.core/delay https://clojuredocs.org/clojure.core/future

like image 84
iced Avatar answered Jan 09 '23 13:01

iced


future creates a Future and schedules it for execution immediately, therefore calling

(get-document "id")

will cause a future to be created which fetches the document immediately and then caches the result in the future.

In contrast, delay creates a lazy operation which will not be executed until dereferenced. In this case, calling

(get-document "id")

will not cause the document to be fetched. This will only happen when dereferencing e.g.

(let [{:keys [content]} (get-document "id")]
  (println @content))
like image 21
Lee Avatar answered Jan 09 '23 12:01

Lee