Loading [MathJax]/extensions/TeX/AMSsymbols.js

Saturday, June 29, 2013

Clojure vectors vs. PersistentQueue

Clojure has several pre-built data structures that can be used to implement our ideas. Here you have a comparison of the well-known vector and the poorly-documented clojure.lang.PersistentQueue.
=> (let [q (into (clojure.lang.PersistentQueue/EMPTY) (range 1000))]
(time
(loop [q3 q]
(let [e (peek q3)]
(if-not (nil? e)
(do
(recur (pop q3)) ))))))
"Elapsed time: 0.624344 msecs"
view raw time-queue.clj hosted with ❤ by GitHub
=> (let [v (vec (range 1000))]
(time
(loop [v2 v]
(let [e (first v2)]
(if-not (nil? e)
(recur (subvec v2 1)) )))) )
"Elapsed time: 0.864674 msecs"
view raw time-vector.clj hosted with ❤ by GitHub
Edit: I changed the code in quotes to a Github Gist since I like it much better the way it looks. Sorry for the horrible contrast of the gists and the blogger template, I believe nothing will save me from modifiying the colors.

There was a fatal flaw in the implementation. It is now corrected. Thanks to the commentators.