问题
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