Skip to content

Instantly share code, notes, and snippets.

@slipset
Created April 15, 2019 11:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slipset/12af01dfac0632d4dbe40a32d96b9e8c to your computer and use it in GitHub Desktop.
Save slipset/12af01dfac0632d4dbe40a32d96b9e8c to your computer and use it in GitHub Desktop.
(def urls {:vg "https://www.vg.no", :ap "https://www.ap.no", :db "https://www.db.no"} )
(defn my-get-request [[k url]]
[k (future (http/get url))])
(->> urls
(map my-get-request)
(reduce (fn [acc [k v]]
(assoc acc k (deref v))) {}))
@heralden
Copy link

Looks like map does the same thing as for, and returns a lazy seq, so you still need a doall to avoid chunked realization of the futures.

(defn my-get-request [x] [x (future (do (Thread/sleep 1000) x))])

(time (->> (range 0 100) (map my-get-request) (reduce (fn [m [k v]] (assoc m k (deref v))) {})))
; => "Elapsed time: 4010.6218 msecs"

(time (->> (range 0 100) (map my-get-request) doall (reduce (fn [m [k v]] (assoc m k (deref v))) {})))
; => "Elapsed time: 1025.489758 msecs"

@slipset
Copy link
Author

slipset commented Apr 15, 2019

I know that map is as lazy as for, but the thing is that reduce is not. It would be interesting if you could add some timings to this.

@slipset
Copy link
Author

slipset commented Apr 15, 2019

Yeah! I see where the problem comes from now :)

(defn my-get [i]
  [i (future (:status (http/get "https://www.vg.no")))])

(->> (range 100)
     (map my-get)
     (reduce (fn [acc [k v]]
               (let [t (System/currentTimeMillis)
                     v' (deref v)]
                 (println "Spent " (- (System/currentTimeMillis) t) "ms dreffing" k)
                 (assoc acc k 'v))) {}))

You'll see time spent on every 32nd element, indicating that the thing is not done as we'd like.

@slipset
Copy link
Author

slipset commented Apr 15, 2019

(defn my-get [i]
  [i (future (:status (http/get "https://www.vg.no")))])

(defn transmogrify [acc [k v]]
  (let [t (System/currentTimeMillis)
        v' (deref v)]
    (println "Spent " (- (System/currentTimeMillis) t) "ms dreffing" k)
    (assoc acc k v')))

(->> (range 100)
     (reduce (fn [acc i] (conj acc (my-get i))) [])
     (reduce transmogrify {}))

does the thing :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment