scala - Source.fromFile 的效率

标签 scala

我想知道以下代码片段的效率是多少:

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使用上面的nexthasNext来派生列表。所以 lst 已经包含了文件的所有元素。

执行 lst.contains(x) 会像任何其他列表一样迭代该列表。

关于scala - Source.fromFile 的效率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17939759/

相关文章:

scala - lambda 的缩写形式在内部函数中不起作用

ruby-on-rails - 高性能 REST API - 哪种语言/堆栈?

scala - 使用 spark-sql 查询时,时间戳字段失去精度

scala - 如何构建使用 sbt 作为构建系统的项目?

scala - Spark 结构化流 + Kafka 集成 : MicroBatchExecution PartitionOffsets Error

scala - 如何在编译时失败而不是运行时异常

java - 无法扩展以前版本的 Scala(scala 2.11.4、sbt 0.13.7、JDK 8)编译的宏

scala - 删除 SBT 项目并删除 Typesafe Stack

json - Play Framework 2.1 中的 Scala 到 JSON

scala - 类型构造函数是单子(monad)还是有单子(monad)?