Skip to content

Instantly share code, notes, and snippets.

@moxaj
Created November 1, 2016 23:54
Show Gist options
  • Save moxaj/a6851ad7fb5b75a497289c5d9f34f6b4 to your computer and use it in GitHub Desktop.
Save moxaj/a6851ad7fb5b75a497289c5d9f34f6b4 to your computer and use it in GitHub Desktop.
vector iteration
(ns foo.bar
(:require [criterium.core :as c])
(:import [clojure.lang Indexed Counted]))
(defmacro c! [& form]
`(c/with-progress-reporting (c/quick-bench (do ~@form))))
(defn fn1 [u]
(dotimes [i (.count ^Counted u)]
(.nth ^Indexed u (unchecked-int i))))
(defn fn2 [u]
(doseq [x u]
x))
(defn fn3 [u]
(let [c (.count ^Counted u)]
(loop [i (unchecked-dec c)]
(if (== i 0)
nil
(let [x (.nth ^Indexed u (unchecked-int i))]
(recur (unchecked-dec i)))))))
(def x (vec (range 1000)))
(c! (fn1 x)) ;; 2.42us
(c! (fn2 x)) ;; 1.26us
(c! (fn3 x)) ;; 2.41us
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment