不可变类会节省内存吗?
我自己实现的不可变类会节省内存吗?也就是说,如果两个引用需要引用相同的实例,则即使有两次单独的对象分配尝试,它们也将引用同一实例。这是一个Java问题。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不是不变性,而是您的设计使两个引用引用同一实例,这才是“节省”内存的原因。不变性独立于该决定。
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.
你混淆了概念。类是不可变的这一事实并不意味着您将“重用”以前的对象。
例如,如果我这样做,
我就创建了两个不同的对象(即使它们的 equals() 实现返回 true)。
另一件事是池/缓存,您可以在其中保留已创建实例的列表,并且不调用构造函数,而是调用可以获取先前缓存的实例的工厂方法。不可变类更容易池化/缓存,因为它们的状态仅取决于构造函数,因此您可以确定它没有更改。
当然,如果您的实例很少被重用,您将最终使用此模式更多的内存。
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
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.
Of course, if your instances are sheldom reused you would end using more memory with this schema.