Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
(defn len [x]
(.length x))
(defn len2 [^String x]
(.length x))
(defprotocol ILengthable
(len3 [this]))
(extend-protocol ILengthable
(len3 [this] (.length this)))
;; protocols are fast as type hint
(time (reduce + (map len (repeat 1000000 "asdf"))))
;; "Elapsed time: 3638.889732 msecs"
(time (reduce + (map len2 (repeat 1000000 "asdf"))))
;; "Elapsed time: 209.107647 msecs"
(time (reduce + (map len3 (repeat 1000000 "asdf"))))
;; "Elapsed time: 211.155188 msecs"
;; protocols has way better error messages
(len nil)
;; Execution error (NullPointerException) at user/len (form-init9161877390498479258.clj:3).
;; null
(len2 nil)
;; Execution error (NullPointerException) at user/len2 (form-init9161877390498479258.clj:6).
;; null
(len3 nil)
;; Execution error (IllegalArgumentException) at user/eval59854$fn$G (form-init9161877390498479258.clj:7).
;; No implementation of method: :len3 of protocol: #'user/ILengthable found for class: nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.