Disadvantages of Immutable objects says:
The disadvantage of immutable classes is that their instances need to be copied first, whereas an update could be done in its place.
That means using a huge and immutable object to run the same process could have worse performance than a same mutable one, correct?
That makes sense because an immutable object needs to be duplicated in advance each time it is operated.
[hadoop@nn1 scala]$ cat Im.scala
// Im.scala
object Im extends App {
val valBigInt: BigInt = 999999999999999999L
var varBigIntTmp: BigInt = 0L
for(i<- 1L to 99999999L) {
varBigIntTmp = valBigInt.flipBit(0)
}
}
[hadoop@nn1 scala]$ cat M.scala
// M.scala
object M extends App {
var varBigInt: BigInt = 999999999999999999L
var varBigIntTmp: BigInt = 0L
for(i<- 1L to 99999999L) {
varBigIntTmp = varBigInt.flipBit(0)
}
}
I kept interpreting both of them many times.
Im.scala always consumes less "real time" than M.scala.
For example,
[hadoop@nn1 scala]$ time scala Im.scala
real 0m8.878s
user 0m12.228s
sys 0m1.940s
[hadoop@nn1 scala]$ time scala M.scala
real 0m9.890s // is greater than the real time (8.878s) of Im.scala
user 0m14.070s
sys 0m1.383s
That seems Immutable objects would not have the disadvantages above, why?