我想知道以下片段的效率是什么?
val lst = Source.fromFile(f).getLines.toList在发布lst.contains(x)时,
这是否意味着f正在被重新扫描,还是搜索依赖于新创建的列表中f的内存内容?
提前谢谢。
发布于 2013-07-30 06:34:25
搜索依赖于内存中的内容。而且它只加载了一次toList被调用。
如何更好地直接从来源看到。Source.fromFile返回一个scala.io.BufferedSource。getLines返回一个BufferedLineIterator。
它在BufferedLineIterator中,文件的内容被读取。
override def hasNext = {
if (nextLine == null)
nextLine = lineReader.readLine
nextLine != null
}
override def next(): String = {
val result = {
if (nextLine == null) lineReader.readLine
else try nextLine finally nextLine = null
}
if (result == null) Iterator.empty.next
else result
}
}调用toList使用上面的next和hasNext派生列表。所以lst已经包含了文件的所有元素。
执行lst.contains(x)会像任何其他列表一样迭代列表。
发布于 2013-07-30 07:05:13
一旦您使用toList,它将返回不可变列表给您操作。您的文件将不会为您正在进行的列表中的操作重新打包。
https://stackoverflow.com/questions/17939759
复制相似问题