我正在运行以下Scala代码:
import scala.util.parsing.json._
import scala.io._
object Main {
def jsonStringMap(str: String) =
JSON.parseFull(str) match {
case Some(m: Map[_,_]) => m collect {
// If this doesn't match, we'll just ignore the value
case (k: String, v: String) => (k,v)
} toMap
case _ => Map[String,String]()
}
def main(args: Array[String]) {
val fh = Source.fromFile("listings.txt")
try {
fh.getLines map(jsonStringMap) foreach { v => println(v) }
} finally {
fh.close
}
}
}
在我的机器上,处理 http://sortable.com/blog/coding-challenge/ 文件大约需要 3 分钟的时间。我编写的等效 Haskell 和 Ruby 程序只需要不到 4 秒钟的时间。我做错了什么?
我尝试了没有 map(jsonStringMap) 的相同代码,速度非常快,所以 JSON 解析器真的很慢吗?
似乎默认的 JSON 解析器确实很慢,但是我尝试了 https://github.com/stevej/scala-json,虽然速度降至 35 秒,但仍比 Ruby 慢得多。
我现在使用 https://github.com/codahale/jerkson,它甚至更快!我的程序现在在我的数据上只需要 6 秒钟,比 Ruby 慢了 3 秒钟,这可能只是 JVM 启动时的差异。