Scala 流及其内存使用 [英] Scala streams and their memory usage

查看:38
本文介绍了Scala 流及其内存使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,Stream 保留了最近评估的元素.我猜它不会保留所有评估的元素(这是不可行的),所以它可能使用了一些内部缓存".

As I understand, Stream retains the recently evaluated elements. I guess it does not retain all evaluated elements (it is not feasible), so it probably uses some internal "cache".

正确吗?我可以控制这个缓存的大小和策略吗?

Is it correct? Can I control the size and policies of this cache?

推荐答案

流就像列表,根据需要生成其成员.一旦生成了一个元素,它就会保留在流中并被重用.

Streams are like lists that generate their members as they are required. Once an element has been generated, it is retained in the stream and reused.

例如:

lazy val naturals: Stream[Int] = Stream.cons(0, naturals.map{_ + 1})

会给你一个自然数流.如果我打电话

will give you a stream of the natural numbers. If I call

naturals(5)

它会生成元素 0-5 并返回 5,如果我然后调用

it will generate elements 0-5 and return 5, if I then call

naturals(8)

它将重用前 6 个元素并生成另外 3 个.

It will reuse the first 6 elements and generate 3 more.

如果你担心内存使用,你可以使用 Stream.drop(num) 来产生一个新的流,其中 num 元素从头开始被删除,允许截断要与旧流一起垃圾收集的元素.例如:

If you are concerned about memory usage, you can use Stream.drop(num) to produce a new stream with num elements removed from the beginning, allowing the truncated elements to be garbage collected with the old stream. For example:

naturals(5) //returns 5
val truncated = naturals.drop(4)
truncated(5) //returns 9

这篇关于Scala 流及其内存使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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