本文介绍了我什么时候应该在 Scala 中选择 Vector?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看来Vector参加Scala合集晚会迟到了,所有有影响力的博文都已经离开了.

It seems that Vector was late to the Scala collections party, and all the influential blog posts had already left.

在 Java 中 ArrayList 是默认集合 - 我可能会使用 LinkedList 但只有当我已经考虑过算法并足够关心优化时才会使用.在 Scala 中,我应该使用 Vector 作为我的默认 Seq,还是尝试找出 List 实际上更合适?

In Java ArrayList is the default collection - I might use LinkedList but only when I've thought through an algorithm and care enough to optimise. In Scala should I be using Vector as my default Seq, or trying to work out when List is actually more appropriate?

推荐答案

作为一般规则,默认使用 Vector.对于几乎所有内容,它都比 List 快,对于比平凡大小的序列而言,它的内存效率更高.请参阅此 文档 与其他 Vector 相比的相对性能集合.使用 Vector 有一些缺点.具体:

As a general rule, default to using Vector. It’s faster than List for almost everything and more memory-efficient for larger-than-trivial sized sequences. See this documentation of the relative performance of Vector compared to the other collections. There are some downsides to going with Vector. Specifically:

  • 头部的更新比 List 慢(虽然没有你想象的那么多)
  • Updates at the head are slower than List (though not by as much as you might think)

Scala 2.10 之前的另一个缺点是模式匹配支持对 List 更好,但是在 2.10 中使用通用的 +::+ 提取器.

Another downside before Scala 2.10 was that pattern matching support was better for List, but this was rectified in 2.10 with generalized +: and :+ extractors.

还有一种更抽象的代数方式来解决这个问题:你概念上有什么样的序列?另外,你概念上用它做什么?如果我看到一个返回 Option[A] 的函数,我知道该函数在其域中有一些漏洞(因此是部分的).我们可以将同样的逻辑应用于集合.

There is also a more abstract, algebraic way of approaching this question: what sort of sequence do you conceptually have? Also, what are you conceptually doing with it? If I see a function that returns an Option[A], I know that function has some holes in its domain (and is thus partial). We can apply this same logic to collections.

如果我有一个 List[A] 类型的序列,我有效地断言了两件事.首先,我的算法(和数据)完全是堆栈结构的.其次,我断言我要对这个集合做的唯一事情是满的,O(n) 次遍历.这两个真的是相辅相成的.相反,如果我有 Vector[A] 类型的东西,我断言唯一的事情是我的数据具有明确定义的顺序和有限长度.因此,Vector 的断言较弱,这导致其更大的灵活性.

If I have a sequence of type List[A], I am effectively asserting two things. First, my algorithm (and data) is entirely stack-structured. Second, I am asserting that the only things I’m going to do with this collection are full, O(n) traversals. These two really go hand-in-hand. Conversely, if I have something of type Vector[A], the only thing I am asserting is that my data has a well defined order and a finite length. Thus, the assertions are weaker with Vector, and this leads to its greater flexibility.

这篇关于我什么时候应该在 Scala 中选择 Vector?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 06:33