Skip to content

Instantly share code, notes, and snippets.

@nivekuil
Created January 11, 2024 13:42
Show Gist options
  • Save nivekuil/7a9f682afa253c4c320d7a73411f4a4d to your computer and use it in GitHub Desktop.
Save nivekuil/7a9f682afa253c4c320d7a73411f4a4d to your computer and use it in GitHub Desktop.
fast hash types
(deftype IdAttr [id attr ^:mutable ^number _hasheq]
IEquiv
(-equiv
[this that]
(boolean
(or (identical? this that)
(and (instance? IdAttr that)
(= id (.-id ^IdAttr that))
(= attr (.-attr ^IdAttr that))))))
IIndexed
(-nth [coll n] (-nth coll n nil))
(-nth [coll n not-found] (case n, 0 id, 1 attr, not-found))
IHash
(-hash [o]
(if (zero? _hasheq)
(set! _hasheq (+ (* 31 (hash id)) (hash attr)))
_hasheq)))
(deftype IdAttrs [last-object h]
IStack
(-peek [coll] last-object)
ICollection
(-conj [coll o]
(IdAttrs. o (+ h (* 31 (hash o)))))
IEquiv
(-equiv
[this that]
(boolean (or (identical? this that)
(and (instance? IdAttrs that)
(= h (.-h ^IdAttrs that))
(= last-object (.-last-object ^IdAttrs that))))))
IHash
(-hash [o] h))
(comment
(simple-benchmark []
(get {(into [(->IdAttr 1 :foo 0)]
[(->IdAttr 1 :foo 0)
(->IdAttr 1 :foo 0)])
1}
(into [(->IdAttr 1 :foo 0)]
[(->IdAttr 1 :foo 0)
(->IdAttr 1 :foo 0)]))
100000)
(simple-benchmark []
(get {(into
(IdAttrs. (->IdAttr 1 :foo 0) (* 31 (hash (->IdAttr 1 :foo 0))))
[(->IdAttr 1 :foo 0)
(->IdAttr 1 :foo 0)])
1}
(into
(IdAttrs. (->IdAttr 1 :foo 0) (* 31 (hash (->IdAttr 1 :foo 0))))
[(->IdAttr 1 :foo 0)
(->IdAttr 1 :foo 0)]))
100000)
(simple-benchmark []
(= (->IdAttr 1 :foo 0)
(->IdAttr 1 :foo 0))
1000000)
(simple-benchmark [] (= [1 :foo] [1 :foo])
1000000)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment