Into or vec: converting sequence back to vector in Clojure

Viewed 11178

I have the following code which increments the first element of every pair in a vector:

(vec (map (fn [[key value]] [(inc key) value]) [[0 :a] [1 :b]]))

However i fear this code is inelegant, as it first creates a sequence using map and then casts it back to a vector.

Consider this analog:

(into [] (map (fn [[key value]] [(inc key) value]) [[0 :a] [1 :b]]))

On #clojure@irc.freenode.net i was told, that using the code above is bad, because into expands into (reduce conj [] (map-indexed ...)), which produces many intermediate objects in the process. Then i was told that actually into doesn't expand into (reduce conj ...) and uses transients when it can. Also measuring elapsed time showed that into is actually faster than vec.

So my questions are:

  1. What is the proper way to use map over vectors?
  2. What happens underneath, when i use vec and into with vectors?

Related but not duplicate questions:

1 Answers
Related