Search code examples
vectorclojure

vector-of vs. vector in Clojure


When would I use vector-of to create a vector, instead of the vector function. Is the guideline to use vector most of the time and only for performance reason switch to vector-of?

I could not find good info on when to use vector-of.


Solution

  • vector-of is used for creating a vector of a single primitive type, :int, :long, :float, :double, :byte, :short, :char, or :boolean. It doesn't allow other types as it stores the values unboxed internally. So, if your vector need to include other types than those primitive types, you cannot use vector-of. But if you are sure that the vector will have data of a single primitive type, you can use vector-of for better performance.

    user=> (vector-of :int 1 2 3 4 5)
    [1 2 3 4 5]
    user=> (vector-of :double 1.0 2.0)
    [1.0 2.0]
    user=> (vector-of :string "hello" "world")
    Execution error (IllegalArgumentException) at user/eval5 (REPL:1).
    Unrecognized type :string
    

    As you can see, you should specify primitive type as an argument.

    vector can be used to create a vector of any type.

    user=> (vector 1 2.0 "hello")
    [1 2.0 "hello"]
    

    You can put any type when you use vector.

    Also, there's another function vec, which is used for creating a new vector containing the contents of coll.

    user=> (vec '(1 2 3 4 5))
    [1 2 3 4 5]
    

    Usually, you can get the basic information of a function/macro from the repl, like the following.

    user=> (doc vector-of)
    -------------------------
    clojure.core/vector-of
    ([t] [t & elements])
      Creates a new vector of a single primitive type t, where t is one
      of :int :long :float :double :byte :short :char or :boolean. The
      resulting vector complies with the interface of vectors in general,
      but stores the values unboxed internally.
    
      Optionally takes one or more elements to populate the vector.
    

    Reference: