I'm trying to optimize my app against memory leaks. I've read A LOT of blog posts and SO questions, and I've seen some people saying to deference statically declared variables so the GC can collect them, while others saying it's unnecessary.
public class MyActivity extends Activity {
private static Context context;
private static ArrayList<String> arrayList = new Arraylist<>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
arrayList.add("Random strings");
..//Other code
}
@Override
protected void onDestroy() {
context = null;
arrayList.clear();
super.onDestroy();
}
The reason behind the code is that static variables are independent of activity lifecycles and therefore will implicitly hold the reference for the entire activity context even after onDestroy unless it's reference is null. But I've tested both variants in my app and there weren't any differences from one another. Is the above really necessary?