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.

2
  • Possible duplicate of Can immutable be a memory hog? Commented Nov 20, 2016 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? Commented Nov 20, 2016 at 11:34

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
I see. The question never mentions any specific Scala implementation so i only about JVM which is most popular i believe.
@Michal, I think that your answer was helpful from the JVM perspective. Thanks for the answer.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.