onDestroy() - to set or not to set instance variables to null?

╄→гoц情女王★ 提交于 2019-12-30 16:48:02

问题


Is it a good idea to specifically set the instance variables to null in onDestroy() callback of the activity? Something like this:

    @Override
protected void onDestroy() {
    super.onDestroy();
    mClassVariable1 = null;
    mClassVariable2 = null;
    mClassVariable3 = null;
}

If I remember correctly from Java SE, any references that are isolated & not connected to a running program & can be garbage collected anyways. So does this make the above superfluous?

On the other hand, the lifecycle in mobile devices being different, would the above be a best-practice?

I know it cannot hurt to do it, but sometimes there are a number of class variable (references to indivudual UI elements etc), so I'd really like to know for my own understanding, what's really going on.

Thanks in advance!


回答1:


You had it right when you said that the garbage collector will pick up references that are isolated. Specifically, any graph of references not connected to the execution thread will be collected. Because of this, there is no good reason to set your variables to null that I can see. Any advantages would be far outweighed by the code maintenance cost.



来源:https://stackoverflow.com/questions/5582962/ondestroy-to-set-or-not-to-set-instance-variables-to-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!