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.