流 vs 视图 vs 迭代器 [英] Stream vs Views vs Iterators

查看:28
本文介绍了流 vs 视图 vs 迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

scala 中的 Streams、Views (SeqView) 和 Iterators 有什么区别?这是我的理解:

What are the differences among Streams, Views (SeqView), and Iterators in scala? This is my understanding:

  • 它们都是惰性列表.
  • 流缓存值.
  • 迭代器只能使用一次?不能回到起点重新评估价值吗?
  • 视图的值不会被缓存,但您可以一次又一次地评估它们?

所以如果我想节省堆空间,我应该使用迭代器(如果我不会再次遍历列表)还是视图?谢谢.

So if I want to save heap space, should I use iterators (if I won't traverse the list again) or views? Thanks.

推荐答案

首先,它们都是非严格.这具有与函数相关的特定数学含义,但基本上意味着它们是按需计算的,而不是预先计算的.

First, they are all non-strict. That has a particular mathematical meaning related to functions, but, basically, means they are computed on-demand instead of in advance.

Stream 确实是一个惰性列表.事实上,在 Scala 中,Stream 是一个 List,它的 tail 是一个 lazy val.一旦计算,一个值将保持计算状态并被重用.或者,如您所说,值被缓存.

Stream is a lazy list indeed. In fact, in Scala, a Stream is a List whose tail is a lazy val. Once computed, a value stays computed and is reused. Or, as you say, the values are cached.

Iterator 只能使用一次,因为它是一个遍历指针到一个集合中,而不是一个集合本身.它在 Scala 中的特殊之处在于,您可以应用诸如 mapfilter 之类的转换,并简单地获得一个新的 Iterator,它只会应用当您要求下一个元素时,这些转换.

An Iterator can only be used once because it is a traversal pointer into a collection, and not a collection in itself. What makes it special in Scala is the fact that you can apply transformation such as map and filter and simply get a new Iterator which will only apply these transformations when you ask for the next element.

Scala 曾经提供可以重置的迭代器,但很难以一般方式支持,并且他们没有制作 2.8.0 版本.

Scala used to provide iterators which could be reset, but that is very hard to support in a general manner, and they didn't make version 2.8.0.

视图旨在与数据库视图非常相似.它是应用于集合以产生虚拟"集合的一系列转换.正如您所说,每次您需要从中获取元素时,都会重新应用所有转换.

Views are meant to be viewed much like a database view. It is a series of transformation which one applies to a collection to produce a "virtual" collection. As you said, all transformations are re-applied each time you need to fetch elements from it.

Iterator 和视图都具有出色的内存特性.Stream 很好,但是,在 Scala 中,它的主要好处是编写无限序列(特别是递归定义的序列).但是,一个可以避免将所有 Stream 保留在内存中,方法是确保您不保留对其 head 的引用(例如,通过使用 def 而不是 val 来定义 Stream).

Both Iterator and views have excellent memory characteristics. Stream is nice, but, in Scala, its main benefit is writing infinite sequences (particularly sequences recursively defined). One can avoid keeping all of the Stream in memory, though, by making sure you don't keep a reference to its head (for example, by using def instead of val to define the Stream).

由于视图产生的惩罚,通常应该在应用转换后强制它,或者如果与总大小相比预计只会获取很少的元素,则将其保留为视图视图.

Because of the penalties incurred by views, one should usually force it after applying the transformations, or keep it as a view if only few elements are expected to ever be fetched, compared to the total size of the view.

这篇关于流 vs 视图 vs 迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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