I am working through some Lisp exercises using Clojure. If I were to convert Lisp lists to Clojure vectors, solving some of the problems would be simpler, so here is my question:
Does using vec
or vector
cost a lot in terms of time and/or processing? Does using either function cause a meta state change, or are the values converted and moved to a vector?
2
Both functions return a new vector for you.
vec expect a coll
parameter that will be converted to a vector
vector expect args to create a new vector.
Bellow the excecution time for each one:
vec
user=> (time (vec '(1 2 4)))
;= "Elapsed time: 0.043 msecs"
;= [1 2 4]
vector
user=> (time (vector 1 2 3)))
;= "Elapsed time: 0.025 msecs"
;= [1 2 3]
1
I am using criterium library to measure performance.
I’m seeing better performance for vec than for apply vector
user=> (use 'criterium.core)
nil
user=> (def mylist (range 100))
#'user/mylist
user=> (bench (apply vector mylist))
WARNING: Final GC required 4.142753917114324 % of runtime
Evaluation count : 8356800 in 60 samples of 139280 calls.
Execution time mean : 7.271515 µs
Execution time std-deviation : 112.366680 ns
Execution time lower quantile : 7.066423 µs ( 2.5%)
Execution time upper quantile : 7.485808 µs (97.5%)
Overhead used : 11.772233 ns
nil
user=> (bench (vec mylist))
Evaluation count : 8949480 in 60 samples of 149158 calls.
Execution time mean : 6.647705 µs
Execution time std-deviation : 83.691653 ns
Execution time lower quantile : 6.473123 µs ( 2.5%)
Execution time upper quantile : 6.796003 µs (97.5%)
Overhead used : 11.772233 ns
nil
2