foldLeftとmutableMap

最近Scalaにちょーーっとだけ慣れてきたので、なんとなくvarやmutableな何かをつかったら負けた気分になってしまいます。何かを集計してMapを作る、みたいな処理も嬉々としてfoldLeftつかってやってたら、社内のコードレビューで「インスタンス生成爆発で遅くなるからmutable.Map使った方がよくない?」って。

そ、そんなことないんじゃないのかなあ(動揺)。というわけで調べた。
コード。

val list = List.range(0, 100000)
    for (time <- 1 to 10) {
      val startTime = System.currentTimeMillis()
      val map = list.foldLeft(Map[Int, String]()) {
        (m, i) =>
          m + (i -> ("value" + i))

      }
      println("foldLeft time: " + (System.currentTimeMillis() - startTime))
    }

    for (time <- 1 to 10) {
      val startTime = System.currentTimeMillis()
      val map2 = collection.mutable.Map[Int, String]()
      for (i <- list) {
        map2.put(i, "value" + i)
      }
      println("mutable time:" + (System.currentTimeMillis() - startTime))
    }

結果

foldLeft time: 415
foldLeft time: 137
foldLeft time: 147
foldLeft time: 146
foldLeft time: 154
foldLeft time: 152
foldLeft time: 136
foldLeft time: 136
foldLeft time: 128
foldLeft time: 127
mutable time:137
mutable time:96
mutable time:124
mutable time:84
mutable time:110
mutable time:110
mutable time:85
mutable time:104
mutable time:106
mutable time:107

。。。そりゃそうですよね。
正直、思ったよりfoldLeftは善戦してた。


これから書き直します。