0

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?

Julia Chang
  • 181
  • 1
  • 8
  • 2
    I couldn't find documentation for the BigInt class online. However, it is unlikely how it is implemented will change my answer. From what I can see, since you never reassign varBigInt, the only difference between the two programs is the time to allocate valBigInt and varBigInt initially. – Allen Han Nov 11 '19 at 17:45
  • 2
    You're not testing what you think you are. "val a" just says you can't change what a refers to. It does NOT say that what a refers to is immutable. Similarly, "var b" does not imply what what b refers to is mutable. In both your test cases. valBigInt and varBigInt hold the same type (scala.math.BigInt) which is immutable. – The Archetypal Paul Nov 11 '19 at 18:42
  • 4
    Aside from "microbenchmarking is hard", you're also timing compilation. 2.12 has a `-nc` option to force compilation, which is default in 2.13. "You're not testing what you think you are." – som-snytt Nov 11 '19 at 19:21
  • @som-snytt, I would recode both programs with proper immutable and mutable classes respectively someday. Yet 1. I should use "User+Sys" to measure the performance. https://stackoverflow.com/questions/556405/what-do-real-user-and-sys-mean-in-the-output-of-time1 2. "Microbenchmarking is hard." & "We should forget about small efficiencies." https://stackoverflow.com/questions/2842695/what-is-microbenchmarking Thanks. – Julia Chang Nov 12 '19 at 07:47

0 Answers0