循环中的不可变对象创建

时间:2021-05-27 04:17:48

From my understanding creating mutable objects inside of a loop like the method below would create a bunch of objects which would the garbage collection would have to dispose of each new object.

根据我的理解,在循环内部创建可变对象,就像下面的方法一样,会创建一堆对象,垃圾收集必须处理每个新对象。

for (int i=0; i<1000000000; i++){
    Object obj = new Object();
}

As opposed to this method which reuses the same object and doesn’t require garbage collection.

与此方法相反,该方法重用相同的对象并且不需要垃圾回收。

Object obj;
for (int i=0; i<1000000000; i++){
    obj = new Object();
}

But what about when using immutable objects that cannot be changed after they are instantiated? The garbage collection would still have to run on these objects regardless, correct? If so, then in this case does either of these methods make any difference in regards to garbage collection and performance?

但是当使用在实例化后无法更改的不可变对象时呢?无论如何,垃圾收集仍然必须在这些对象上运行,对吗?如果是这样,那么在这种情况下,这些方法中的任何一个在垃圾收集和性能方面都有所不同吗?

Say for example the object is a BigDecimal:

比如说对象是一个BigDecimal:

for (int i=0; i<1000000000; i++){
    BigDecimal number = new BigDecimal(someValue);
}

VS.

BigDecimal number;
for (int i=0; i<1000000000; i++){
    number = new BigDecimal(someValue);
}

Is there any difference in these two now that we’re dealing with immutable objects?...excluding scope, I am aware of the difference in scope in these two examples. Thanks!

现在我们正在处理不可变对象,这两个有什么不同吗?...除了范围,我知道这两个例子的范围不同。谢谢!

1 个解决方案

#1


As opposed to this method which reuses the same object and doesn’t require garbage collection.

与此方法相反,该方法重用相同的对象并且不需要垃圾回收。

No, each scenario you describe will create objects that need garbage collected.

不,您描述的每个场景都会创建需要收集垃圾的对象。

Is there any difference in these two now that we’re dealing with immutable objects?

现在我们处理不可变对象,这两个有什么区别吗?

No. Although some immutable objects such as String and Integer types may be cached by the VM.

不可以。虽然VM可以缓存一些不可变对象,如String和Integer类型。

#1


As opposed to this method which reuses the same object and doesn’t require garbage collection.

与此方法相反,该方法重用相同的对象并且不需要垃圾回收。

No, each scenario you describe will create objects that need garbage collected.

不,您描述的每个场景都会创建需要收集垃圾的对象。

Is there any difference in these two now that we’re dealing with immutable objects?

现在我们处理不可变对象,这两个有什么区别吗?

No. Although some immutable objects such as String and Integer types may be cached by the VM.

不可以。虽然VM可以缓存一些不可变对象,如String和Integer类型。