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

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

问题描述

在Java中为 null 分配一个未使用的对象引用是否以任何可衡量的方式改善垃圾收集过程?

我对Java(和C#)的使用经验告诉我,通常会违背虚拟机或JIT编译器的智慧,但我见过同事使用这种方法,我很好奇这是否是一种很好的做法拿起或其中一个巫术编程迷信?

解决方案

通常情况下,不。



但是像所有的事情一样:这取决于。现在Java中的GC非常好,一切都应该在不再可及时很快清理掉。这是在离开一个局部变量的方法之后,并且当一个类实例不再被字段引用时。



如果你知道它将保留,你只需要显式地为null否则引用。例如一个数组,它保持在周围。您可能希望在不再需要数组的各个元素时将它们置空。



例如,来自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; //让gc完成它的工作

return oldValue;
}

另外,显式地将对象置零不会使对象更早收集比如,只要没有任何引用就自然超出了范围。



两者:

  void foo(){
Object o = new Object();
///用o
做的东西

  void foo(){
Object o = new Object();
///用o
做东西o = null;
}

在功能上是等同的。


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

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?

解决方案

Typically, no.

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.

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.

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.

Both:

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

and:

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

Are functionally equivalent.

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

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