Scala Infinite Iterator OutOfMemory
发布时间:2020-12-16 18:11:10 所属栏目:安全 来源:网络整理
导读:我正在玩 Scala的懒惰迭代器,我遇到了一个问题.我要做的是读取一个大文件,进行转换,然后写出结果: object FileProcessor { def main(args: Array[String]) { val inSource = Source.fromFile("in.txt") val outSource = new PrintWriter("out.txt") try { /
我正在玩
Scala的懒惰迭代器,我遇到了一个问题.我要做的是读取一个大文件,进行转换,然后写出结果:
object FileProcessor { def main(args: Array[String]) { val inSource = Source.fromFile("in.txt") val outSource = new PrintWriter("out.txt") try { // this "basic" lazy iterator works fine // val iterator = inSource.getLines // ...but this one,which incorporates my process method,// throws OutOfMemoryExceptions val iterator = process(inSource.getLines.toSeq).iterator while(iterator.hasNext) outSource.println(iterator.next) } finally { inSource.close() outSource.close() } } // processing in this case just means upper-cases every line private def process(contents: Seq[String]) = contents.map(_.toUpperCase) } 所以我在大文件上得到一个OutOfMemoryException.我知道如果你保持对流的头部的引用,你可以与Scala的懒惰流相遇.所以在这种情况下,我小心翼翼地将process()的结果转换为迭代器并抛弃最初返回的Seq. 有谁知道为什么这仍会导致O(n)内存消耗?谢谢! 更新 为了回应fge和huynhjl,似乎Seq可能是罪魁祸首,但我不知道为什么.作为一个例子,以下代码工作正常(我在整个地方使用Seq).此代码不会产生OutOfMemoryException: object FileReader { def main(args: Array[String]) { val inSource = Source.fromFile("in.txt") val outSource = new PrintWriter("out.txt") try { writeToFile(outSource,process(inSource.getLines.toSeq)) } finally { inSource.close() outSource.close() } } @scala.annotation.tailrec private def writeToFile(outSource: PrintWriter,contents: Seq[String]) { if (! contents.isEmpty) { outSource.println(contents.head) writeToFile(outSource,contents.tail) } } private def process(contents: Seq[String]) = contents.map(_.toUpperCase) 解决方法
正如fge暗示的那样,修改进程以获取迭代器并删除.toSeq. inSource.getLines已经是一个迭代器.
转换为Seq将导致记住项目.我认为它会将迭代器转换为Stream并导致所有项目都被记住. 编辑:好的,它更加微妙.您通过在进程的结果上调用迭代器来执行Iterator.toSeq.iterator的等效操作.这可能会导致内存不足异常. scala> Iterator.continually(1).toSeq.iterator.take(300*1024*1024).size java.lang.OutOfMemoryError: Java heap space 这可能与此处报告的问题相同:https://issues.scala-lang.org/browse/SI-4835.请注意我在错误结尾处的评论,这是来自个人经验. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- angularjs – ui-bootstrap-tpls.min.js和ui-boo
- twitter-bootstrap – Bootstrap glyphicons显示
- angularjs – SignalR客户端方法在角度服务中多次
- 盘点Linux平台下的高可用集群软件(High Availabi
- 单元测试 – Angular2如何对自定义验证器指令进行
- angularjs – 如何使用Angular JS将值推送到数组
- Angular学习:控制器(未翻译完)
- actionscript-3 – AS3时间戳不正确
- 斯卡拉:什么是特质TraversableOnce? Traversab
- 分享一个适用于bootstrap且优化后的codeigniter分
热点阅读