-
-
Save tomjack/bf8f747e4ffa29591665 to your computer and use it in GitHub Desktop.
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
(ns scratch.mapcat | |
(:use [clojure.set :only (union)])) | |
(defn divisors [n] | |
(filter (comp zero? (partial mod n)) | |
(range 2 n))) | |
(defn mapcat2 [f & colls] | |
(reduce concat (apply map f colls))) | |
(defn reduce-vs-apply [] | |
(println "apply:") | |
(time (dorun (mapcat divisors (range 1000)))) | |
(println "reduce:") | |
(time (dorun (mapcat2 divisors (range 1000))))) | |
;; apply: | |
;; "Elapsed time: 1723.707991 msecs" | |
;; reduce: | |
;; "Elapsed time: 6491.475802 msecs" | |
;; (defn mapunion [f & colls] | |
;; (reduce into (cons #{} (apply map f colls)))) | |
(defn mapunion [f & colls] | |
(->> (apply map f colls) | |
(cons (transient #{})) | |
(reduce (partial reduce conj!)) | |
persistent!)) | |
(defn mapcat-vs-mapunion [] | |
(println "mapcat:") | |
(time (dorun (mapcat divisors (range 2000)))) | |
(println "mapunion:") | |
(time (dorun (mapunion divisors (range 2000))))) | |
;; mapcat: | |
;; "Elapsed time: 6523.554967 msecs" | |
;; mapunion: | |
;; "Elapsed time: 6505.352707 msecs" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment