2013-07-30 43 views
4

我不知道什么是下面的代码片断的效率:效率Source.fromFile

val lst = Source.fromFile(f).getLines.toList 

当发出lst.contains(x)

岂不是f正在重新扫描,或者是它的情况下搜索是否依靠新创建的列表中的f的内存内容?

在此先感谢。

回答

4

搜索依赖于内存中的内容。它只被调用一次toList被调用。

如何更好地从source直接看到。 Source.fromFile返回scala.io.BufferedSourcegetLines返回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使用nexthasNext上面导出列表。所以lst已经包含了文件的所有元素。

lst.contains(x)遍历列表作为任何其他列表。

2

一旦使用了toList,它将向您返回不可变列表进行操作。您的文件将不会被重新扫描,您正在执行的操作列表中您有