我正在玩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)
}
Run Code Online (Sandbox Code Playgroud)
所以我在大文件上得到一个OutOfMemoryException.我知道如果你保持对流的头部的引用,你可以与Scala的懒惰流相遇.所以在这种情况下,我小心翼翼地将process()的结果转换为迭代器并抛弃最初返回的Seq.
有谁知道为什么这仍会导致O(n)内存消耗?谢谢!
为了回应fge和huynhjl,似乎Seq可能是罪魁祸首,但我不知道为什么.作为一个例子,以下代码工作正常(我在整个地方使用Seq).此代码并不会产生一个OutOfMemoryException:
object …Run Code Online (Sandbox Code Playgroud)