Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save petrounias/c36155896e9380fe6b921100b038f3ea to your computer and use it in GitHub Desktop.
Save petrounias/c36155896e9380fe6b921100b038f3ea to your computer and use it in GitHub Desktop.
Clojure find first performance comparison
; Comparing performance of 'normal' versus transducer 'find-first' in Clojure, where:
;
; (find-first (fn [thing] (number? thing)) [:foo 'bar 42 "zog" 67])
; => 42
; Normal version
(defn find-first
"Normal version."
[pred coll]
(first (filter pred coll)))
(crit/quick-bench
(find-first (fn [thing] (number? thing)) [:foo 'bar 42 "zog" 67]))
; Evaluation count : 5201808 in 6 samples of 866968 calls.
; Execution time mean : 120,802605 ns
; Execution time std-deviation : 10,748634 ns
; Execution time lower quantile : 113,533652 ns ( 2,5%)
; Execution time upper quantile : 137,823274 ns (97,5%)
; Overhead used : 1,593551 ns
; Transducer version
(defn find-first-xform
"Transducer version."
([pred]
(fn [rf]
(fn
([] (rf))
([result] (rf result))
([result v]
(if (pred v)
(ensure-reduced (rf result v))
result)))))
([pred coll]
(reduce (fn [_ v] (if (pred v) (reduced v))) nil coll)))
(crit/quick-bench
(find-first-xform (fn [thing] (number? thing)) [:foo 'bar 42 "zog" 67]))
; Evaluation count : 30099960 in 6 samples of 5016660 calls.
; Execution time mean : 18,852101 ns
; Execution time std-deviation : 0,220444 ns
; Execution time lower quantile : 18,605147 ns ( 2,5%)
; Execution time upper quantile : 19,149294 ns (97,5%)
; Overhead used : 1,593551 ns
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment