Permalink
Browse files

hash-set and faster set construction

  • Loading branch information...
1 parent 49bff84 commit c60df78e2fd318109a9338a87277c11565b506ae @brandonbloom brandonbloom committed with David Nolen Jun 25, 2012
Showing with 33 additions and 8 deletions.
  1. +7 −1 benchmark/cljs/benchmark_runner.cljs
  2. +4 −2 src/clj/cljs/compiler.clj
  3. +19 −5 src/cljs/cljs/core.cljs
  4. +3 −0 test/cljs/cljs/core_test.cljs
@@ -109,6 +109,12 @@
(simple-benchmark [coll cljs.core.PersistentHashMap/EMPTY] (assoc coll :f0 1) 1000000)
(println)
+(println ";;; set ops")
+(simple-benchmark [] #{} 100000)
+(simple-benchmark [] #{1 2 3} 100000)
+(simple-benchmark [coll #{1 2 3}] (conj coll 4) 100000)
+(println)
+
(println ";;; seq ops")
(simple-benchmark [coll (range 500000)] (reduce + coll) 1)
(println)
@@ -135,4 +141,4 @@
(simple-benchmark [r r] (last r) 1)
(println)
-(println "\n")
+(println "\n")
@@ -249,8 +249,10 @@
(defmethod emit :set
[{:keys [items env]}]
(emit-wrap env
- (emits "cljs.core.set(["
- (comma-sep items) "])")))
+ (if (empty? items)
+ (emits "cljs.core.PersistentHashSet.EMPTY")
+ (emits "cljs.core.PersistentHashSet.fromArray(["
+ (comma-sep items) "])"))))
(defmethod emit :constant
[{:keys [form env]}]
@@ -5589,6 +5589,15 @@ reduces them without incurring seq initialization"
(set! cljs.core.PersistentHashSet/EMPTY (PersistentHashSet. nil (hash-map) 0))
+(set! cljs.core.PersistentHashSet/fromArray
+ (fn [items]
+ (let [len (count items)]
+ (loop [i 0
+ out (transient cljs.core.PersistentHashSet/EMPTY)]
+ (if (< i len)
+ (recur (inc i) (conj! out (aget items i)))
+ (persistent! out))))))
+
(deftype TransientHashSet [^:mutable transient-map]
ITransientCollection
(-conj! [tcoll o]
@@ -5696,14 +5705,19 @@ reduces them without incurring seq initialization"
(set! cljs.core.PersistentTreeSet/EMPTY (PersistentTreeSet. nil (sorted-map) 0))
+(defn hash-set
+ ([] cljs.core.PersistentHashSet/EMPTY)
+ ([& keys]
+ (loop [in (seq keys)
+ out (transient cljs.core.PersistentHashSet/EMPTY)]
+ (if (seq in)
+ (recur (next in) (conj! out (first in)))
+ (persistent! out)))))
+
(defn set
"Returns a set of the distinct elements of coll."
[coll]
- (loop [in (seq coll)
- out (transient cljs.core.PersistentHashSet/EMPTY)]
- (if (seq in)
- (recur (next in) (conj! out (first in)))
- (persistent! out))))
+ (apply hash-set coll))
(defn sorted-set
"Returns a new sorted set with supplied keys."
@@ -488,8 +488,11 @@
(assert (set []))
(assert (= #{} (set [])))
+ (assert (= #{} (hash-set)))
+ (assert (identical? cljs.core.PersistentHashSet (type (hash-set))))
(assert (= #{"foo"} (set ["foo"])))
+ (assert (= #{"foo"} (hash-set "foo")))
(assert (= #{1 2 3} #{1 3 2}))
(assert (= #{#{1 2 3} [4 5 6] {7 8} 9 10}
#{10 9 [4 5 6] {7 8} #{1 2 3}}))

0 comments on commit c60df78

Please sign in to comment.