迭代器方法和视图方法有什么区别?
scala> (1 to 10).iterator.map{_ * 2}.toList
res1: List[Int] = List(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)
scala> (1 to 10).view.map{_ * 2}.force
res2: Seq[Int] = Vector(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)
除了使用 next、hasNext 之外,什么时候应该选择迭代器而不是视图或视图而不是迭代器?
scala> (1 to 10).iterator.map{_ * 2}.toList
res1: List[Int] = List(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)
scala> (1 to 10).view.map{_ * 2}.force
res2: Seq[Int] = Vector(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)
Other than using next,hasNext, when should I choose iterator over view or view over iterator?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
迭代器和视图之间存在巨大差异。迭代器只使用一次,按需计算,而视图则使用多次,每次都重新计算,但只计算需要的元素。例如:
There's a huge difference between iterators and views. Iterators are use once only, compute on demand, while views are use multiple times, recompute each time, but only the elements needed. For instance:
view
生成一个惰性集合/流。它的主要魅力在于它不会尝试构建整个集合。当您只需要集合中的前几个项目时,这可以防止 OutOfMemoryError 或提高性能。iterator
不做这样的保证。还有一件事。至少在
Range
上,view
返回一个SeqView
,它是Seq
的子类型,因此您可以返回或从头开始并执行所有有趣的顺序操作。我想迭代器和视图之间的区别在于前面和后面的问题。迭代器预计会发布已经看到的内容。一旦
next
被调用,前一个就有望被释放。观点则相反。他们承诺不会获取未要求的东西。如果你有一个所有素数的视图,一个无限的集合,它只获得了你所要求的那些素数。如果你想要第 100 个,那么 101 应该还没有占用内存。view
produces a lazy collection/stream. It's main charm is that it won't try and build the whole collection. This could prevent a OutOfMemoryError or improve performance when you only need the first few items in the collection.iterator
makes no such guarantee.One more thing. At least on
Range
,view
returns aSeqView
, which is a sub-type ofSeq
, so you can go back or start again from the beginning and do all that fun sequency stuff.I guess the difference between an iterator and a view is a matter of in-front and behind. Iterators are expected to release what has been seen. Once
next
has been called, the previous is, hopefully, let go. Views are the converse. They promise to not acquire what has not been requested. If you have a view of all prime numbers, an infinite set, it has only acquired those primes you've asked for. It you wanted the 100th, 101 shouldn't be taking up memory yet.此页面讨论何时使用视图。
This page talks about when to use views.