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

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

问题描述

如何在序列生成操作(如排序)之后将序列转换回向量?在作为向量的序列上使用 (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]))

我之所以这么问是因为我需要随机访问(第 n 个 ..)到巨大的排序向量 - 现在排序后的序列很大,具有可怕的 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

P.S.:请注意,矢量版本实际上并未在任何地方存储已排序的矢量,但这不会显着改变结果,因为您会在循环中使用简单绑定来提高速度.

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天全站免登陆