Clojure:序列回到向量 [英] Clojure: sequence back to vector

查看:121
本文介绍了Clojure:序列回到向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在序列生成操作(如sort)后将序列转换回向量?在作为向量的序列上使用(vec ..)是昂贵的吗?

How can I cast a sequence back to vector after a sequence producing operation (like sort)? Does using (vec..) on a sequence that was a vector is costly?

一种可能性是创建一个新的矢量序列:

One (bad?) possibility is creating a new vector out of sequence:

(vec (sort [1 2 3 4 5 6]))

因为我需要随机访问(nth ..)到巨大的排序的向量 - 这是现在是排序后,可怕的O(n)随机访问时间大的序列

I am asking because I need random access (nth ..) to huge sorted vectors - which are now huge sequences after the sort, with horrible O(n) random access time

推荐答案

从我自己的测试(没有科学),你可以更好地直接在数组上工作,在你做大量的排序。但是如果你很少排序,并有很多随机访问做,虽然,使用向量可能是一个更好的选择,因为随机访问时间平均快40%以上,但排序性能是可怕的,由于将向量转换一个数组,然后回到一个向量。这是我的发现:

From my own tests (nothing scientific) you may be better with working directly on arrays in cases where you do lots of sorting. But if you sort rarely and have a lots of random access to do though, going with a vector may be a better choice as random access time is more than 40% faster on average, but the sorting performance is horrible due to converting the vector to an array and then back to a vector. Here's my findings:

(def foo (int-array (range 1000)))

(time
  (dotimes [_ 10000]
    (java.util.Arrays/sort foo)))

; Elapsed time: 652.185436 msecs

(time
  (dotimes [_ 10000]
    (nth foo (rand-int 1000))))

; Elapsed time: 7.900073 msecs

(def bar (vec (range 1000)))

(time
  (dotimes [_ 10000]
    (vec (sort bar))))

; Elapsed time: 2810.877103 msecs

(time
  (dotimes [_ 10000]
    (nth bar (rand-int 1000))))

; Elapsed time: 5.500802 msecs



PS:请注意,向量版本实际上并不存储任何地方,但这不应该改变结果,因为你会使用简单的绑定在一个循环的速度。

P.S.: Note that the vector version doesn't actually store the sorted vector anywhere, but that shouldn't change the result considerably as you would use simple bindings in a loop for speed.

这篇关于Clojure:序列回到向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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