-
-
Save skrat/60a7f8745e6b212a36bf7b492cb4436b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; 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) | |
(simple-benchmark [] (aget-loop-nth test-data ["2" "2" "2"]) 100000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment