Source.fromFile的效率

时间:2013-07-30 06:29:00

标签: scala

我想知道以下代码段的效率是什么:

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

发出lst.contains(x)时,

是否意味着重新扫描f,或者搜索是否依赖于新创建的列表中f的内存内容?

提前致谢。

2 个答案:

答案 0 :(得分: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)会像其他任何列表一样遍历列表。

答案 1 :(得分:2)

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