Skip to content

Instantly share code, notes, and snippets.

@Frozenlock
Forked from skrat/test.cljs
Last active June 16, 2017 13:15
Show Gist options
  • Save Frozenlock/df52cf6d747a8b2be9b71d12934bd907 to your computer and use it in GitHub Desktop.
Save Frozenlock/df52cf6d747a8b2be9b71d12934bd907 to your computer and use it in GitHub Desktop.
;; some speed tests of functions to access nested properties in JS objects.
(def test-data (->> (into {} (for [k1 (range 10)]
[k1 (into {} (for [k2 (range 10)]
[k2 (into {} (for [k3 (range 10)]
[k3 k3]))]))]))
(clj->js)))
(defn aget-apply [o path]
(apply aget o path))
(defn oget-in [js-object path]
(reduce (fn [o p]
(goog.object/getValueByKeys o p)) js-object path))
(defn aget-reduce [o path]
(reduce (fn [o p]
(aget o p)) o path))
(defn aget-loop [o path]
(loop [cur-o o p path]
(let [result
(aget cur-o (first p))]
(if-let [new-path (seq (rest p))]
(recur result new-path)
result))))
(defn aget-loop-nth [o path]
(let [l (count path)]
(loop [cur-o o i 0]
(let [result
(aget cur-o (first p))]
(if-let [new-path (seq (rest p))]
(recur result new-path)
result)))))
(defn aget-reduce-js [o js-path]
(.reduce js-path (fn [o k] (aget o k)) o))
(defn aget-loop-nth [o path]
(let [l (count path)]
(loop [o' o i 0]
(if (< i l)
(recur (aget o' (nth path i)) (inc i))
o'))))
(simple-benchmark [] (aget-apply test-data ["2" "2" "2"]) 100000) ;; --> 339msecs
(simple-benchmark [] (oget-in test-data ["2" "2" "2"]) 100000) ;; --> 208msecs
(simple-benchmark [] (aget-reduce test-data ["2" "2" "2"]) 100000) ;; --> 134msecs
(simple-benchmark [] (aget-loop test-data ["2" "2" "2"]) 100000) ;; --> 84msecs
(simple-benchmark [] (aget-reduce-js test-data #js ["2" "2" "2"]) 100000);; --> 35msecs
(simple-benchmark [] (aget-loop-nth test-data ["2" "2" "2"]) 100000) ;; --> 181msecs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment