在 Java 中将对象分配给 null 会影响垃圾收集吗? [英] Does assigning objects to null in Java impact garbage collection?

查看:36
本文介绍了在 Java 中将对象分配给 null 会影响垃圾收集吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中将未使用的对象引用分配给 null 是否会以任何可衡量的方式改进垃圾收集过程?

Does assigning an unused object reference to null in Java improve the garbage collection process in any measurable way?

我在 Java(和 C#)方面的经验告诉我,尝试超越虚拟机或 JIT 编译器通常是违反直觉的,但我见过同事使用这种方法,我很好奇这是否是好的练习拿起或那些巫毒编程迷信之一?

My experience with Java (and C#) has taught me that is often counter intuitive to try and outsmart the virtual machine or JIT compiler, but I've seen co-workers use this method and I am curious if this is a good practice to pick up or one of those voodoo programming superstitions?

推荐答案

通常不会.

但就像所有事情一样:这取决于.现在 Java 中的 GC 非常好,所有东西都应该在不再可访问后很快被清理干净.这是在为局部变量留下一个方法之后,并且当一个类实例不再被字段引用时.

But like all things: it depends. The GC in Java these days is VERY good and everything should be cleaned up very shortly after it is no longer reachable. This is just after leaving a method for local variables, and when a class instance is no longer referenced for fields.

如果您知道它会以其他方式保持引用,则只需显式为 null.例如,一个保留在周围的数组.当不再需要数组的各个元素时,您可能希望将它们清空.

You only need to explicitly null if you know it would remain referenced otherwise. For example an array which is kept around. You may want to null the individual elements of the array when they are no longer needed.

例如,来自 ArrayList 的这段代码:

For example, this code from ArrayList:

public E remove(int index) {
    RangeCheck(index);

    modCount++;
    E oldValue = (E) elementData[index];

    int numMoved = size - index - 1;
    if (numMoved > 0)
         System.arraycopy(elementData, index+1, elementData, index,
             numMoved);
    elementData[--size] = null; // Let gc do its work

    return oldValue;
}

此外,只要不存在引用,显式清空一个对象不会比它自然超出范围的对象更早地被收集.

Also, explicitly nulling an object will not cause an object to be collected any sooner than if it just went out of scope naturally as long as no references remain.

两者:

void foo() {
   Object o = new Object();
   /// do stuff with o
}

和:

void foo() {
   Object o = new Object();
   /// do stuff with o
   o = null;
}

在功能上是等效的.

这篇关于在 Java 中将对象分配给 null 会影响垃圾收集吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆