I am trying to optimise my code, memory wise, for an Android project I'm working on.
I am looking for a way to minimise the accumulated garbage, my main question would be is it worth injecting (through dagger) variables within a class, if they are to be used just within a specific method (either initialisation or for another purpose) or should I only declare them within the respected method will increase garbage collection after this method is executed?
F.i. is there a case where we want the following case:
@Inject
Foo foo;
@Overrides
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DaggerAppComponent.create().inject(this);
}
public void bar() {
foo.bar();
}
instead of the one below (given that the object will only be used within the bar method)?
@Overrides
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void bar() {
Foo foo = new Foo();
foo.bar();
}
Isn't the second case more memory efficient, rendering the object ready for the garbage collector?
Last, is there any case where it would be recommended to use System.gc()?
Thank you!