Skip to content

Instantly share code, notes, and snippets.

@nathanmarz
Created August 23, 2011 17:11
Show Gist options
  • Save nathanmarz/1165885 to your computer and use it in GitHub Desktop.
Save nathanmarz/1165885 to your computer and use it in GitHub Desktop.
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