What is the difference in terms of efficiency and under-the-hood details
between
(apply conj [0][1])
and (into [0][1])
?
Using the time
function it seems that apply conj
is faster, but is there a price? and what is it?
The into
function is generally preferable to apply conj
in Clojure due to the following reasons:
Performance: into
is usually faster than apply conj
. The into
function is implemented in a way that allows for optimized, efficient
concatenation of collections. On the other hand, apply conj
involves
using conj
repeatedly with variadic arguments, which can be less
performant.
Simplicity & Readability: into
provides a simpler and more concise
way to concatenate collections. It takes care of the concatenation
internally without requiring explicit iteration or multiple function
calls. Using into makes the code more readable and expressive. It
clearly communicates the intention of concatenating or merging
collections, improving the overall code clarity.
Flexibility: into
supports merging of collections, not just
concatenation. It can merge collections of different types or with
conflicting keys, providing more flexibility in combining data
structures.
That being said, there may be specific cases where apply conj
is more suitable, such as when you need to dynamically pass in collection elements as variadic arguments. However, for most general cases, the into
function is the preferred way to concatenate or merge collections in Clojure.
into
should be significantly faster, since it uses transient sequences, according to it's source. For the short ones conj could be a bit faster since it doesn't use any additional machinery, but forclojure.lang.RT/conj
.time
is not suitable for benchmarking small things. Check out github.com/hugoduncan/criterium(apply conj xs ys)
were better than(into xs ys)
, why would anyone ever useinto
for anything? Why wouldinto
even be defined?"into
could be better simply because it's one word. Since the implementation ofinto
is different, that aroused the question "why is into not implemented withapply conj
"?.