Skip to content

Instantly share code, notes, and snippets.

@mhuebert
Last active November 24, 2019 15:38
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 mhuebert/2781f9d1b2481301a8eb17ce2c5d0e3e to your computer and use it in GitHub Desktop.
Save mhuebert/2781f9d1b2481301a8eb17ce2c5d0e3e to your computer and use it in GitHub Desktop.
comparison of reading a def'd var, object property, and exists? check

compiled js

// read a def
$app$bench$x$$

// read from cache
$app$bench$cache$$.x || 20

// exists?
"undefined" !== typeof $app$$ && "undefined" !== typeof $app$bench$$ && "undefined" !== typeof $app$bench$x$$ ? $app$bench$x$$ : 10

cljs source

;; assign x and cache values later to avoid the compiler inlining values later
(def x nil)
(def cache nil)
(set! x 10)
(set! cache #js{:x 10})

;; wrap in console.log so compiler doesn't throw away results
(js/console.log "read def" x)
(js/console.log "read cache" (js* "~{} || ~{}" (unchecked-get cache "x") 20))
(js/console.log "exists check" (if (exists? x) x 10))

benchmarks

exists?         x 927,315,604 ops/sec ±1.02% (91 runs sampled)
cache           x 932,548,414 ops/sec ±1.18% (90 runs sampled)
def             x 933,832,352 ops/sec ±1.13% (92 runs sampled)

read-from-atom  x 70,540,398 ops/sec ±0.26% (97 runs sampled)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment