我想知道以下代码片段的效率是多少:
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)
会像任何其他列表一样迭代该列表。
关于scala - Source.fromFile 的效率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17939759/