I tried searching stackoverflow and there are a number of relevant topics including
val-mutable versus var-immutable in Scala
What is the difference between a var and val definition in Scala?
But I still want to clarify if my understanding is correct.
Looks like the rule is following
Prefer immutable val over immutable var over mutable val over mutable var. Especially immutable var over mutable val!
But performance of immutable var is much worse vs mutable val according to simple test in REPL
scala -J-Xmx2g
scala> import scala.collection.mutable.{Map => MMap}
import scala.collection.mutable.{Map=>MMap}
scala>
scala> def time[R](block: => R): R = {
| val t0 = System.nanoTime()
| val result = block // call-by-name
| val t1 = System.nanoTime()
| println("Elapsed time: " + (t1 - t0) + "ns")
| result
| }
time: [R](block: => R)R
scala>time {val mut_val = MMap[Int, Int](); for (i <- 1 to 1000000) mut_val += (i -> i)}
Elapsed time: 551073900ns
scala>time {var mut_var = MMap[Int, Int](); for (i <- 1 to 1000000) mut_var += (i -> i)}
Elapsed time: 574174400ns
scala>time {var imut_var = Map[Int, Int](); for (i <- 1 to 1000000) imut_var += (i -> i)}
Elapsed time: 860938800ns
scala>time {val mut_val = MMap[Int, Int](); for (i <- 1 to 2000000) mut_val += (i -> i)}
Elapsed time: 1103283000ns
scala>time {var mut_var = MMap[Int, Int](); for (i <- 1 to 2000000) mut_var += (i -> i)}
Elapsed time: 1166532600ns
scala>time {var imut_var = Map[Int, Int](); for (i <- 1 to 2000000) imut_var += (i -> i)}
Elapsed time: 2926954500ns
I added also mutable var even tough it does not make much sense. It's performance is quite similar to mutable val, just to complete the picture. But performance of immutable var is much worse.
So the price for immutable var vs mutable val is degraded performance (and more extensive memory usage!). Can someone please explain again what is the point of paying that price? Specific examples are appreciated.
Thanks