Skip to content

Instantly share code, notes, and snippets.

@featalion
Created August 29, 2015 00:51
Show Gist options
  • Select an option

  • Save featalion/bf9badb0574f4a4939f1 to your computer and use it in GitHub Desktop.

Select an option

Save featalion/bf9badb0574f4a4939f1 to your computer and use it in GitHub Desktop.
Comparison of old and new functions of nuday.utils.maps
;;; make & evaluate 4000 maps: {0 0}, {0 0, 1 1}, {0 0, 1 1, 2 2}, etc.
(def maps (doall
(map (fn [n]
(let [rng (range (inc n))]
(zipmap rng rng)))
(range 4000))))
(defn mfilter-old [f input]
(when input
(->> input ; uses macro
(filter #(f (key %) (val %))) ; creates intermediate collection
(into {})))) ; conj each element of the collection w/ map
(defn mfilter-new [f input]
(when input
(reduce (fn [acc [k v]]
(if (f k v)
(assoc acc k v)
acc))
{}
input)))
(time (doseq [m maps] (mfilter-old #(< %2 2) m)))
;;; "Elapsed time: 1197.420274 msecs"
;;; => nil
(time (doseq [m maps] (mfilter-new #(< %2 2) m)))
;;; "Elapsed time: 505.0972 msecs"
;;; => nil
(defn mmap-old [f input]
(when input
(let [f (if (map? input)
#(f (key %) (val %))
#(f %))]
(->> input
(map f) ; creates intermediate collection
(into {}))))) ; conjoins
(defn mmap-new [f input]
(when input
(let [f (if (map? input)
#(f (key %) (val %))
#(f %))]
(reduce #(conj %1 (f %2)) {} input))))
(time (doseq [m maps] (mmap-old #(vector %1 %2) m)))
;;; "Elapsed time: 2531.482558 msecs"
;;; => nil
(time (doseq [m maps] (mmap-new #(vector %1 %2) m)))
;;; "Elapsed time: 2214.766777 msecs"
;;; => nil
;;; {0 0, 1 nil, 2 2, 3 nil, ...}
(def half-nil (let [rng (range 10000)]
(doall (zipmap rng (map #(when (= 0 (rem % 2)) %) rng)))))
;;; Overall complexity of this function is O(N),
;;; where N is number of entries in the map.
;;; It creates a lot of intermediate collections, too.
(defn replace-nils-old [m ks v]
(let [replace? #(and (contains? (set ks) %1) (nil? %2))] ; makes set each call
(->> m
(mmap (fn [k cur-v] [k (if (replace? k cur-v) v cur-v)])))))
;;; Overall complexity is O(N), where N is number of keys
(defn replace-nils-new [m ks v]
(reduce-kv (fn [acc k the-v]
(if (nil? the-v)
(assoc acc k v)
acc))
m
(select-keys m ks)))
(time (do (replace-nils-old half-nil (range 1000) :lol) nil))
;;; "Elapsed time: 2215.009732 msecs"
;;; => nil
(time (do (replace-nils-new half-nil (range 1000) :lol) nil))
;;; "Elapsed time: 2.239303 msecs"
;;; => nil
(time (do (replace-nils-old half-nil (range 10) :lol) nil))
;;; "Elapsed time: 18.533465 msecs"
;;; => nil
(time (do (rep-nils half-nil (range 10) :lol) nil))
;;; "Elapsed time: 0.158874 msecs"
;;; => nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment