我什么时候使用 vector-of
创建一个向量,而不是 vector
功能。是使用指南vector
大多数时间并且仅出于性能原因切换到 vector-of
?
我找不到关于何时使用的好信息 vector-of
.
最佳答案
vector-of
用于创建 的向量单个原始类型 , :int
, :long
, :float
, :double
, :byte
, :short
, :char
, 或 :boolean
.它不允许其他类型,因为它存储内部未装箱的值。因此,如果您的向量需要包含那些原始类型以外的其他类型,则不能使用 vector-of
.但是,如果您确定向量将具有单个原始类型的数据,则可以使用 vector-of
以获得更好的性能。
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
如您所见,您应该将原始类型指定为参数。
vector
可用于创建任何类型的向量。user=> (vector 1 2.0 "hello")
[1 2.0 "hello"]
使用
vector
时可以放任何类型.此外,还有另一个功能
vec
,用于创建一个包含 coll 内容的新向量。user=> (vec '(1 2 3 4 5))
[1 2 3 4 5]
通常,您可以从 repl 中获取函数/宏的基本信息,如下所示。
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.
引用:
关于Clojure 中的向量与向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59158514/