开发者

will a immutable class save memory?

开发者 https://www.devze.com 2023-03-27 20:18 出处:网络
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 s开发者_如何学Goame instance even if

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 s开发者_如何学Goame instance even if there are two separate attempts to allocate the object. This is a Java question.


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号