H2ONaCl
H2ONaCl

Reputation: 11309

will a immutable class save memory?

Will an immutable class of my own implementation result in memory savings? That is, if two references need to refer to identical instances, they will reference the same instance even if there are two separate attempts to allocate the object. This is a Java question.

Upvotes: 0

Views: 1062

Answers (3)

SJuan76
SJuan76

Reputation: 24895

You are confusing concepts. The fact that a class is immutable does not mean that you will "reuse" previous objects.

For instance, if I do

ImmutableClass myImmu = new ImmutableClass(5);
ImmutableClass myImmu2 = new ImmutableClass(5);

I have created two different objects (even if their implementation of equals() returns true).

Another thing is pooling/caching, where you keep a list of created instances and, instead of calling a constructor, you call a Factory method that can get you the a previously cached instance. Immutable classes are easier to pool/cache, because they state depends only of the constructor so you are sure it has not changed.

private static Map<Integer, InmutableClass> pool = ...

public static InmutableClass getInstance(int param) {
  InmutableClass returnValue = pool.get(param);
  if (returnValue == null) {
    returnValue = new InmutableClass(param);
    pool.put(param, returnValue);
  }
  return returnValue;
}

Of course, if your instances are sheldom reused you would end using more memory with this schema.

Upvotes: 0

Joachim Sauer
Joachim Sauer

Reputation: 308269

First of: it's hard to judge if it saves memory, if you don't tell us what to compare it with.

Generally: no, not automatically. Immutable classes don't automatically save memory, they can even lead to increased memory pressure, because you'll need to instantiate a new one, each time you want to change something about it.

That being said, you can get some memory savings out of it, if you share instances a lot: since they are immutable you can avoid doing a defensive copy and just use it. This can improve memory usage.

So to summarize: immutable classes alone don't use more or less memory, usually. The actual savings are in how you use them.

Upvotes: 1

Lukas Eder
Lukas Eder

Reputation: 221380

Not immutability, but your design to make two references reference the same instance is what "saves" memory. Immutability is independent of that decision.

Upvotes: 4

Related Questions