Home > other >  Does a Map.empty and a None take the same about of memory?
Does a Map.empty and a None take the same about of memory?

Time:09-23

If i have a case class that looks like:

case class User(id: String, settings: Map[String, String])

Will there be a difference in terms of memory footprint when I instantiate this object if I defined it like this:

case class User(id: String, settings: Map[String, String] = Map.empty[String, String])

versus

case class User(id: String, settings: Option[Map[String, String]] = None)

So we are comparing a case classes property being either an empty Map, or a None on a option type.

Is there a difference in terms of memory footprint on instances of User?

CodePudding user response:

Both None and Map.empty are objects with no fields, so would have the same memory consumption (on a typical JVM, around 20 bytes is the right order of magnitude).

Note that modeling as an Option[Map] incurs overhead (on a typical JVM, something more like 30 bytes) for every non-empty case. There's thus no memory savings by using None in place of an Map.

The only good reason, at least in my experience, to ever use an Option[Map] is in conjunction with things like macro-derived serialization, where you're modeling that the map might not even have a field in the serialized representation.

CodePudding user response:

None is an object. So, it is already created for you and is reused by every reference.

Now, the question is - which Map is this ? mutable or immutable ?

immutable.Map.empty[A, B] is similar to None in this way. Its just that it has more feilds and will "actually" take more memory, but this difference will be in Bytes and can be ignored.

Whereas mutable.Map.empty[A, B]() will create a new empty map object everytime, you create any instance of this User. So, None will result in less memory compared to mutable.Map.empty[A, B]().

  • Related