Create a gist now

Instantly share code, notes, and snippets.

Benchmark between HashMap with lock vs. persistent map with atom
(defn map-incr-unsafe []
(let [m (java.util.HashMap.)]
(.put m "a" 0)
(doseq [i (range 1000000)]
(let [a (.get m "a")]
(.put m "a" (inc a))
))))
(defn map-incr-safe []
(let [o (Object.)
m (java.util.HashMap.)]
(.put m "a" 0)
(doseq [i (range 1000000)]
(locking o
(let [a (.get m "a")]
(.put m "a" (inc a))
)))))
(defn map-incr-atom []
(let [m (atom {"a" 0})]
(doseq [i (range 1000000)]
(swap! m (fn [m] (assoc m "a" (inc (m "a")))))
)))
user> (time (map-incr-unsafe))
"Elapsed time: 49.981 msecs"
user> (time (map-incr-safe))
"Elapsed time: 190.859 msecs"
user> (time (map-incr-atom))
"Elapsed time: 101.537 msecs"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment