Android 取消未使用对象的最佳做法?它是好还是有缺点?
Android Best Practise to nullify unused objects ? Is it Good or it have disadvantages?
我是 Android,
的新手
在 ondestroy() 方法中清空所有对象是否好?
示例:
public class HelloAndroid extends Activity {
TextView tv = null;
private static int mValue; // a static member here
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tv = new TextView(this);
tv.setText((mValue != 0) ?
("Left-over value = " + mValue) : "This is a new instance");
setContentView(tv);
}
public void onDestroy() {
super.onDestroy();
tv = null;
}
}
完全没有必要。对象将被自动垃圾收集。
理论上,它不应该有任何好处。但是,activity 中的空引用可以帮助减轻您无法控制的内存泄漏的影响,例如 this one in the Google Maps API。
您是否应该始终这样做以防止将来出现此类内存泄漏,这是一个见仁见智的问题。您必须权衡维护额外代码的成本与可能的最小收益。
我是 Android,
的新手在 ondestroy() 方法中清空所有对象是否好?
示例:
public class HelloAndroid extends Activity {
TextView tv = null;
private static int mValue; // a static member here
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tv = new TextView(this);
tv.setText((mValue != 0) ?
("Left-over value = " + mValue) : "This is a new instance");
setContentView(tv);
}
public void onDestroy() {
super.onDestroy();
tv = null;
}
}
完全没有必要。对象将被自动垃圾收集。
理论上,它不应该有任何好处。但是,activity 中的空引用可以帮助减轻您无法控制的内存泄漏的影响,例如 this one in the Google Maps API。
您是否应该始终这样做以防止将来出现此类内存泄漏,这是一个见仁见智的问题。您必须权衡维护额外代码的成本与可能的最小收益。