In Programming in Scala, there is this statement:

For instance an empty mutable map in its default representation of HashMap takes up about 80 bytes and about 16 more are added for each entry that’s added to it. An empty immutable Map is a single object that’s shared between all references, so referring to it essentially costs just a single pointer field.

Why does a mutable map need more space?


Sharing is only part of the answer.

The mutable map has to contain all the fields which will be needed when/if elements are added, since calling methods can't change the class of the object.

With immutable maps, you can have a special class for empty maps, which doesn't need any fields (except the ones it inherits), while single-entry maps have a field for the key and a field for the value and can access them without any extra indirections. Calling methods which add elements just returns a new object of a different class, which isn't a problem.


You've pretty much answered your own question here: the immutable object can be shared between every identical instance of the object, but the mutable one can't because that would mean things go horribly wrong when you add anything to the map.

In theory, the mutable object could have been implemented with copy-on-write semantics which would allow sharing of identical mutable maps, but that isn't the route Scala decided to go down.

  • @@Phillip, Thank you! But I don't understand the sentence "the immutable object can be shared between every identical instance of the object", can you expand it, or give me an example for understanding? – abelard2008 Dec 26 '15 at 9:36
  • Sharing is only a part of it. E.g. single-element maps aren't shared, but the immutable versions still take a lot less memory and perform much better than the mutable versions could. – Alexey Romanov Dec 26 '15 at 12:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.