为什么`vector`实现有多种情况? [英] Why does `vector` implementation have multiple cases?

查看:135
本文介绍了为什么`vector`实现有多种情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是clojure的 矢量

Here's clojure's definition of vector:

(defn vector
  "Creates a new vector containing the args."
  {:added "1.0"
   :static true}
  ([] [])
  ([a] [a])
  ([a b] [a b])
  ([a b c] [a b c])
  ([a b c d] [a b c d])
  ([a b c d & args]
     (. clojure.lang.LazilyPersistentVector (create (cons a (cons b (cons c (cons d args))))))))

为什么会有这么多情况?或者,如果有这么多,为什么不会有更多?

Why are there so many cases? Or, if there are so many, why aren't there more?

我的猜测是,在实现效率和概率之间取得平衡,但我不是看看如何更有效率。

My guess is that it's striking a balance between implementation efficiency and probability, but I don't quite see how this would be more efficient.

推荐答案

4似乎在效率的平衡时,

4 seems to strike a balance of efficiency between when there are lots of arguments and when there are not many arguments.

例如:

(defn vector-few
  ([] [])
  ([ & args ] (. clojure.lang.LazilyPersistentVector (create args))))


(defn vector-many
  ([] [])
  ([a] [a])
  ([a b] [a b])
  ([a b c] [a b c])
  ([a b c d] [a b c d])
  ([a b c d e] [a b c d e])
  ([a b c d e f] [a b c d e f])
  ([a b c d e f & args] (. clojure.lang.LazilyPersistentVector (create (cons a (cons b (cons c (cons d (cons e (cons f args))))))))))

使用4个元素运行测试:

Running a test with 4 elements:

=> (time (dotimes [x 1000000] (vector 1 2 3 4)))
"Elapsed time: 12.082104 msecs"

=> (time (dotimes [x 1000000] (vector-few 1 2 3 4)))
"Elapsed time: 443.056339 msecs"

=> (time (dotimes [x 1000000] (vector-many 1 2 3 4)))
"Elapsed time: 11.812106 msecs"

然后使用5:

=> (time (dotimes [x 1000000] (vector 1 2 3 4 5)))
"Elapsed time: 467.904979 msecs"

=> (time (dotimes [x 1000000] (vector-few 1 2 3 4 5)))
"Elapsed time: 537.080198 msecs"

=> (time (dotimes [x 1000000] (vector-many 1 2 3 4 5)))
"Elapsed time: 10.30695 msecs"

和8(所有的函数都使用var-args):

And with 8 (so all of the functions are using the var-args case):

=> (time (dotimes [x 1000000] (vector 1 2 3 4 5 6 7 8)))
"Elapsed time: 832.803266 msecs"

=> (time (dotimes [x 1000000] (vector-few 1 2 3 4 5 6 7 8)))
"Elapsed time: 689.526288 msecs"

=> (time (dotimes [x 1000000] (vector-many 1 2 3 4 5 6 7 8)))
"Elapsed time: 905.95839 msecs"

这篇关于为什么`vector`实现有多种情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆