Created
August 23, 2011 17:11
-
-
Save nathanmarz/1165885 to your computer and use it in GitHub Desktop.
Benchmark between HashMap with lock vs. persistent map with atom
This file contains 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
(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