什么是集合视图?您何时想使用它们?
在 Scala 中,您可以为许多(所有?)类型的集合创建视图。
视图到底是什么?视图可用于哪些目的?
In Scala, for many (all?) types of collections you can create views.
What exactly is a view and for which purposes are views useful?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
视图是集合的非严格版本。这意味着元素是在访问时计算的,而不是像普通集合中那样急切地计算。
以下面的代码为例:
这不会打印任何内容,但每次访问列表都会执行计算并打印值,即每次调用
ys.head
都会得到1正在打印。如果您想再次获得集合的严格版本,您可以对其调用
force
。在这种情况下,您将看到打印出的所有数字。视图的一个用途是当您需要遍历一组值时,这些值的计算成本很高,并且一次只需要一个值。此外,视图还允许您通过调用 toStream 来构建惰性序列,这也将缓存计算的元素。
Views are non-strict versions of collections. This means that the elements are calculated at access and not eagerly as in normal collections.
As an example take the following code:
Just this will not print anything but every access to the list will perform the calculation and print the value, i.e. every call to
ys.head
will result in1
being printed. If you want to get a strict version of the collection again you can callforce
on it. In this case you will see all numbers printed out.One use for views is when you need to traverse a collection of values which are expensive to compute and you only need one value at a time. Also views let you build lazy sequences by calling
toStream
on them that will also cache the evaluated elements.一个用例是当您需要收集元素转换的第一个结果时:
打印:
While:
打印:
One use case is when you need to collect first result of elements transformation:
Prints:
While:
Prints:
请参阅 视图,来自 Scala 2.8 集合 API。
See Views from Scala 2.8 Collections API.
视图用于惰性计算,但不用于节省内存。
当您针对集合创建视图时,已经为该集合分配了内存。
当使用
val view = Range(1,9).view.
创建视图时,集合已经分配了内存,如果太大,例如Range(1,1000000000 )
,OOM无法避免view is used for lazy computation,but not for saving memory.
When you create a view against a collection, the memory has already been allocated forthe collection.
When creating the view with
val view = Range(1,9).view.
, the collection has already been allocated the memory, if it is too large,say,Range(1,1000000000)
, OOM can't be avoid