我已将Scala 函数式编程linesGt1
第 15 章开头的命令式行计数代码(请参阅 参考资料)翻译成使用scalaz-stream的解决方案(请参阅参考资料)。然而,它的表现并不是那么出色。命令式代码比我的 scalaz-stream 解决方案快大约 30 倍。所以我想我在做一些根本错误的事情。如何提高 scalaz-stream 代码的性能?linesGt2
linesGt2
这是我的完整测试代码:
import scalaz.concurrent.Task
import scalaz.stream._
object Test06 {
val minLines = 400000
def linesGt1(filename: String): Boolean = {
val src = scala.io.Source.fromFile(filename)
try {
var count = 0
val lines: Iterator[String] = src.getLines
while (count <= minLines && lines.hasNext) {
lines.next
count += 1
}
count > minLines
}
finally src.close
}
def linesGt2(filename: String): Boolean =
scalaz.stream.io.linesR(filename)
.drop(minLines)
.once
.as(true)
.runLastOr(false)
.run
def time[R](block: => R): R = {
val t0 = System.nanoTime()
val result = block
val t1 = System.nanoTime()
println("Elapsed time: " + (t1 - t0) / 1e9 + "s")
result
}
time(linesGt1("/home/frank/test.txt")) //> Elapsed time: 0.153122057s
//| res0: Boolean = true
time(linesGt2("/home/frank/test.txt")) //> Elapsed time: 4.738644606s
//| res1: Boolean = true
}