0

I understand that scala supports immutability and so when we if we have two integer vals and we do val1 + val2, so it will create a new integer which will have the value as val1 + val2.

My question is that because scala creates new instances of objects to not to mutate the previous object, what are the performance and memory drawbacks of immutability?

Edit: I want details specific to scala about how it deals with the performance and memory overheads.

Maulik Soneji
  • 177
  • 2
  • 15
  • Possible duplicate of [Can immutable be a memory hog?](http://stackoverflow.com/questions/2527412/can-immutable-be-a-memory-hog) – Michał Nov 20 '16 at 11:33
  • @Michal, I am having this question specific to scala. What are the performance and memory enhancements that scala has internally to support immutability? – Maulik Soneji Nov 20 '16 at 11:34

2 Answers2

2

Scala code is compiled to JVM bytecode so basically memory management does not differ compared to Java. Chapter 6 of Programming in Scala, First Edition mentions potential trade-offs of using immutable memory. Potentially you may create many instances of objects but Scala libraries usually create short-lived objects so the garbage collector should deal with them quickly.

Michał
  • 2,456
  • 4
  • 26
  • 33
  • There are multiple implementations of Scala. Two are production-ready: Scala-JVM on the Java platform and Scala.js on the ECMAScript platform. Scala-native is in development, Scala.NET is abandoned. You are confusing the Scala Programming Language with one of the several Scala compilers. – Jörg W Mittag Nov 20 '16 at 11:51
  • 1
    I see. The question never mentions any specific Scala implementation so i only about JVM which is most popular i believe. – Michał Nov 20 '16 at 11:53
  • @Michal, I think that your answer was helpful from the JVM perspective. Thanks for the answer. – Maulik Soneji Nov 20 '16 at 12:46
0

Note that, if you want, you can use var-s and mutable structures, which can, well, mutate. Examples:

var i = 1
i += 1
val l = mutable.Map(1 -> 5)
l += (2 -> 4)  // this one was writte from memory, may need a correction
VasiliNovikov
  • 9,681
  • 4
  • 44
  • 62