Clojure Remove item from Vector at a Specified Location

后端 未结 8 895
无人共我
无人共我 2020-12-04 01:35

Is there a way to remove an item from a vector based on index as of now i am using subvec to split the vector and recreate it again. I am looking for the reverse of assoc fo

8条回答
  •  天命终不由人
    2020-12-04 01:51

    subvec is fast ; combined with transients it gives even better results.

    Using criterium to benchmark:

    user=> (def len 5)
    user=> (def v (vec (range 0 5))
    user=> (def i (quot len 2))
    user=> (def j (inc i))
    
    ; using take/drop
    user=> (bench
             (vec (concat (take i v) (drop j v))))
    ;              Execution time mean : 817,618757 ns
    ;     Execution time std-deviation : 9,371922 ns
    
    ; using subvec
    user=> (bench
             (vec (concat (subvec v 0 i) (subvec v j len))))
    ;              Execution time mean : 604,501041 ns
    ;     Execution time std-deviation : 8,163552 ns
    
    ; using subvec and transients
    user=> (bench
             (persistent!
              (reduce conj! (transient (vec (subvec v 0 i))) (subvec v j len))))
    ;              Execution time mean : 307,819500 ns
    ;     Execution time std-deviation : 4,359432 ns
    

    The speedup is even greater at greater lengths ; the same bench with a len equal to 10000 gives means: 1,368250 ms, 953,565863 µs, 314,387437 µs.

提交回复
热议问题