android - Should I explicitly deference a statically declared Context variable? -
i'm trying optimize app against memory leaks. i've read lot of blog posts , questions, , i've seen people saying deference statically declared variables 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 code static variables independent of activity lifecycles , therefore implicitly hold reference entire activity context after ondestroy unless it's reference null. i've tested both variants in app , there weren't differences 1 another. above necessary?
i'm trying optimize app against memory leaks.
then perhaps should not introducing memory leaks in first place. rid of private static context context
, consider getting rid of private static arraylist<string> arraylist
.
in standard java, non-constant static
fields considered serious code smell. used bit more commonly in android, there clear reason so, , cache, , then more smarts managing cache.
but i've tested both variants in app , there weren't differences 1 another
you see difference if add leakcanary project. without setting static
field null
, leaking activity instance until such time process terminated, or until such time instance of activity created (as replace old field value).
Comments
Post a Comment