Skip to content

Instantly share code, notes, and snippets.

@rauhs
Created January 10, 2017 09:52
Show Gist options
  • Select an option

  • Save rauhs/d012bd43558eac322e96614eab3d76b5 to your computer and use it in GitHub Desktop.

Select an option

Save rauhs/d012bd43558eac322e96614eab3d76b5 to your computer and use it in GitHub Desktop.
(defn sort-by-
"A faster sort-by for clojure.
See http://dev.clojure.org/jira/browse/CLJ-1402"
([keyfn coll]
(sort-by- keyfn compare coll))
([keyfn ^java.util.Comparator comp coll]
(if (seq coll)
(let [ary (object-array (count coll))]
(loop [i 0 xs (seq coll)]
(when xs
(let [x (first xs)]
(aset ary i (object-array [(keyfn x) x]))
(recur (inc i) (next xs)))))
(. java.util.Arrays
(sort ary (fn [x y] (. comp (compare (aget ^{:tag "[Ljava.lang.Object;"} x 0)
(aget ^{:tag "[Ljava.lang.Object;"} y 0))))))
(map (fn [x] (aget ^{:tag "[Ljava.lang.Object;"} x 1)) ary))
())))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment