2012-07-04 16 views
14

這裏是vector Clojure的定義:爲什麼`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)))))))) 

爲什麼有這麼多的情況下?或者,如果有這麼多,爲什麼沒有更多?

我的猜測是它在實現效率和概率之間取得了平衡,但我不太明白這將如何更有效率。

回答

22

4當有大量參數和沒有多少參數時,似乎會達到效率的平衡。

作爲一個例子:

(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種元素的測試:

=> (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情況):

=> (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" 
相關問題