我不知道什么是下面的代码片断的效率:效率Source.fromFile
val lst = Source.fromFile(f).getLines.toList
当发出lst.contains(x)
,
岂不是f
正在重新扫描,或者是它的情况下搜索是否依靠新创建的列表中的f
的内存内容?
在此先感谢。
我不知道什么是下面的代码片断的效率:效率Source.fromFile
val lst = Source.fromFile(f).getLines.toList
当发出lst.contains(x)
,
岂不是f
正在重新扫描,或者是它的情况下搜索是否依靠新创建的列表中的f
的内存内容?
在此先感谢。
搜索依赖于内存中的内容。它只被调用一次toList
被调用。
如何更好地从source直接看到。 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)
遍历列表作为任何其他列表。
一旦使用了toList,它将向您返回不可变列表进行操作。您的文件将不会被重新扫描,您正在执行的操作列表中您有