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 thats added to it. An empty immutable Map is a single object thats shared between all references, so referring to it essentially costs just a single pointer field. Why does a mutable map need more space?
Why does an immutable object in Scala need less memory than a mutable one?
scala;immutability;mutable
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.