删除引用以帮助GC是否是一种很好的做法? [英] Is it a good practice to remove references to help the GC?
问题描述
我想知道您是否认为将对象的引用(将它们设置为 null
)设置为对象以帮助Java垃圾收集器是一种很好的做法。
例如,假设您有一个包含两个字段的类,其中一个字段非常耗费内存。如果你知道你只需要一个特定的处理,你可以在帮助GC之后立即将它清空。
假设我真的需要这两个字段,而不是只有内部变量,所以 heavyObject1
不能在方法结束时超出范围。 你会这样做吗?作为一般做法吗?
public class TestClass {
public static Object heavyObject1;
public static Object object2;
private static void action(){
object2 = doSomething(heavyObject1);
heavyObject1 = null; //这个好吗?
}
}
通常这是不需要的。
在以下特定情况下,这是个好主意:
但是,如果您发现自己处于这种情况下,我怀疑您有设计异味:为什么内部对象有这样的不同封闭对象的范围/生命周期?这让我感到怀疑,因为通常当你用合成建立一个对象图时,你期望合成对象的生命期相似。
I am wondering whether you would consider it a good practice to remove references (setting them to null
) to objects in order to help the Java Garbage Collector.
For instance, let's say you have a class with two fields, one of them being very memory-consuming. If you know you only need it for a particular processing, you can null it right after to help the GC.
Assume I really need those two to be fields, and not only internal variables, so heavyObject1
cannot be out of scope at the end of the method.
Would you do this as a general practice?
public class TestClass {
public static Object heavyObject1;
public static Object object2;
private static void action() {
object2 = doSomething(heavyObject1);
heavyObject1 = null; //is this good?
}
}
Usually it isn't needed.
It's a good idea in the following specific circumstance:
- The object is large (i.e. large enough for you to care)
- You are sure the object won't be needed again
- The object won't go out of scope otherwise (e.g. you know the surrounding object won't be garbage collected)
However if you find yourself in this situation I suspect you have a design smell anyway: why does the internal object have such a different scope / lifetime from the enclosing object? This makes me suspicious, because usually when you build up an object graph with composition you expect the composed objects to have similar lifetimes.
这篇关于删除引用以帮助GC是否是一种很好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!