dolist vs mapcar
;;; dashtest.el --- benchmarking dash -*- lexical-binding: t -*- | |
(defmacro --map-mapcar (form list) | |
(declare (debug (form form))) | |
`(mapcar (lambda (it) ,form) ,list)) | |
(defmacro --map-loop (form list) | |
(declare (debug (form form))) | |
(let ((result-sym (make-symbol "result"))) | |
`(let (,result-sym) | |
(dolist (it ,list) | |
(push ,form ,result-sym)) | |
(nreverse ,result-sym)))) | |
(defun wh/benchmark () | |
(interactive) | |
(let ((small-list (-repeat 1 'foo)) | |
(medium-list (-repeat 1000 'foo)) | |
(large-list (-repeat 100000 'foo))) | |
(message | |
"Small list with mapcar (seconds): %s" | |
(car (benchmark-run 10 (--map-mapcar it small-list)))) | |
(message | |
"Small list with loop (seconds): %s" | |
(car (benchmark-run 10 (--map-loop it small-list)))) | |
(message | |
"Medium list with mapcar (seconds): %s" | |
(car (benchmark-run 10 (--map-mapcar it medium-list)))) | |
(message | |
"Medium list with loop (seconds): %s" | |
(car (benchmark-run 10 (--map-loop it medium-list)))) | |
(message | |
"Large list with mapcar (seconds): %s" | |
(car (benchmark-run 10 (--map-mapcar it large-list)))) | |
(message | |
"Large list with loop (seconds): %s" | |
(car (benchmark-run 10 (--map-loop it large-list)))))) | |
;; Small list with mapcar (seconds): 1.0259000000000001e-05 | |
;; Small list with loop (seconds): 2.8387e-05 | |
;; Medium list with mapcar (seconds): 0.0027399819999999997 | |
;; Medium list with loop (seconds): 0.007948615 | |
;; Large list with mapcar (seconds): 0.7446324980000001 | |
;; Large list with loop (seconds): 1.236648743 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
abo-abo commentedMar 6, 2017
I got with
emacs -batch -l mapcar-test.elc
(replace-repeat
withmake-list
):Overall, not surprising. But the loop is faster for the small list on my system.
Here,
dolist
andmapcar
are used for consing a list -dolist
would be faster thanmapcar
if you were accumulating instead of consing.