Skip to content

Instantly share code, notes, and snippets.

@souenzzo
Created May 7, 2019 14:56
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 souenzzo/431988728c4206bfa445dd9eab1f535b to your computer and use it in GitHub Desktop.
Save souenzzo/431988728c4206bfa445dd9eab1f535b to your computer and use it in GitHub Desktop.
(defn len [x]
(.length x))
(defn len2 [^String x]
(.length x))
(defprotocol ILengthable
(len3 [this]))
(extend-protocol ILengthable
String
(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