将变量和对象设置为null有帮助吗?

时间:2016-01-21 08:37:47

标签: java android performance object null

我想优化我的代码,并提出一些问题。如果我这样做:

TextView currentConsole = (TextView)findViewById(R.id.txt_Mainactvt_currentConsole);
String currentConsoleName = currentConsole.getText().toString();
currentConsole = null;
FloatingActionButtonClickEvent(currentConsoleName);

将对象设置为null是一种好方法,还是没用?

1 个答案:

答案 0 :(得分:1)

垃圾收集器跟踪对您的对象的引用,当没有指向某个对象的指针时,它被标记为删除。它不会立即删除。因此,当您编写currentConsole = null;时,您只需告诉gc控制台对象应该被删除,它将在下一个垃圾收集中。

要优化你可以调用System.gc();这将触发收集,但是gc可能会选择忽略它,所以不能保证在空赋值后删除控制台对象。

垃圾收集间隔是在运行时计算的,主要取决于对象的数量和新分配的频率,所以你能做的最好的事情就是让GC完成它的工作,在大多数情况下他做的最好

最后关于一般的空分配,是的,它们在极少数情况下很有用,请考虑此代码

void testGCMethod()
{
    //Create very big object
    VeryBigObjectType o = new VeryBigObjectType();
    //do dometinh with o
    o.someMethod();

    //Do something that takes long time to complete that doesn't involve o
    Thread.sleep(1000 * 1000 * 1000);
}// end of method meaning the o pointer has just been freed and the big object has just been marked for deletion.

因此在这种情况下(如果JIT没有重新排列代码),VeryBigObjectType实例将在内存中保留整个时间,因此一些开发人员喜欢将o分配给null,以便尽快收集GC

void testGCMethod()
{
    //Create very big object
    VeryBigObjectType o = new VeryBigObjectType();
    //do dometinh with o
    o.someMethod();
    o=null;


    //Do something that takes long time to complete that doesn't involve o
    Thread.sleep(1000 * 1000 * 1000);
}// end of method meaning the o pointer has just been freed and the big 

这样大的对象将被删除(可能)在Thread.sleep之前并保存一些内存;