Skip to content

Instantly share code, notes, and snippets.

@minikomi
Created May 26, 2017 04:23
Show Gist options
  • Save minikomi/a536cbcd8c476437bd78f2d1735c3c90 to your computer and use it in GitHub Desktop.
Save minikomi/a536cbcd8c476437bd78f2d1735c3c90 to your computer and use it in GitHub Desktop.
(ns objtest.core
(:require [goog.object :as gobj]))
(enable-console-print!)
(defrecord Result [title time])
(defn run-all [& tests]
(->>
(for [[title f] tests]
(let [start (js/Date.)]
(println "running:" title)
(dotimes [n 1000] (assert (= {:a 49995000} (f))))
(Result. title (- (js/Date.) start))))
(sort-by :time)
vec
clj->js
(.table js/console)))
(defn init []
(run-all
["get and set!"
(fn []
(let [obj #js{:a 0}]
(dotimes [x 10000]
(set! (.-a obj) (+ (.-a obj) x)))
(js->clj obj :keywordize-keys true)))]
["reduce immutable assoc"
(fn []
(reduce #(assoc % :a (+ (:a %) %2))
{:a 0}
(range 10000)))]
["reduce immutable update"
(fn []
(reduce #(update % :a + %2)
{:a 0}
(range 10000)))]
["dotimes volatile vswap!"
(fn []
(deref
(let [vol (volatile! {:a 0})]
(dotimes [x 10000]
(vswap! vol (fn [v] (update v :a + x))))
vol)))]
["reduce volatile vreset!"
(fn []
(deref
(let [vol (volatile! {:a 0})]
(dotimes [x 10000]
(vreset! vol {:a (+ (:a @vol) x)}))
vol)))]
["reduce volatile vreset! destructure"
(fn []
(deref
(let [vol (volatile! {:a 0})]
(dotimes [x 10000]
(let [{:keys [a]} @vol]
(vreset! vol {:a (+ a x)})))
vol)))]
["gobj get and set!"
(fn []
(let [obj #js{:a 0}]
(dotimes [x 10000]
(gobj/set obj "a" (+ (gobj/get obj "a") x)))
(js->clj obj :keywordize-keys true)))]
["transients"
(fn []
(let [obj (transient {:a 0})]
(dotimes [x 10000]
(assoc! obj :a (+ (:a obj) x)))
(persistent! obj)))]
))
@minikomi
Copy link
Author

screen shot 2017-05-26 at 13 23 42

@minikomi
Copy link
Author

Advanced Optimization:
screen shot 2017-05-26 at 13 28 19

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment