Welcome! Please see the About page for a little more info on how this works.

+3 votes
in Collections by
edited by

I can create set/map/vector by two ways:

(into #{} xs) ;; creates PersistentHashSet
(set xs)      ;; creates PersistentHashSet

(into {} xs)  ;; creates PersistentArrayMap or PersistentHashMap (depends on xs size) 
(apply hash-map xs) ;; creates PersistentHashMap

(into [] xs)  ;; creates PersistentVector
(vec xs)      ;; creates PersistentVector

(into r xs):
- defines generic algorithm by conj!-ing input sequence 1 by 1 to passed result collection (uses transient/persistent trick)

(ctor xs):
- defines precisely type of result data structure
- passes xs sequence as an argument to constructor (which is static java function) so every ctor may define its own logic of creation (maybe by not conj-ing input sequence 1 by 1)

Are there any performance differences between these two ways?
Maybe there is an established idiom what to use when?

Thanks!

1 Answer

+2 votes
by
selected by
 
Best answer

This isn't exactly right in that hash-map does not take xs, it takes individual key value elements, like (hash-map :a 1 :b 2) vs (into {} [[:a 1] [:b 2]]). For that one, what you have in hand will drive. If you have a collection of pairs then into is preferred. If you are building a literal map, it's probably best to just use { ... } and make a literal map vs hash-map (which you will rarely use unless as a higher order function).

The implementations for vec and set are similar to what you'll get with into (reduction over elements into transient collection), so I would expect performance to be similar. vec and set are shorter to type, but into can take transducers, so that's the tradeoff.

by
"This isn't exactly right in that hash-map does not take xs, it takes individual key value elements, like (hash-map :a 1 :b 2) vs (into {} [[:a 1] [:b 2]])."

my bad -- fixed

"I would expect performance to be similar"
got it! thanks

Looked at vec function implementation i was confused by some "adopt" tricks in the body of create static method and supposed some internal useful perf tricks.
...