0

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!

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
ChrisZ
  • 81
  • 9
  • See [In Android, Should not be use System.gc()?](https://stackoverflow.com/q/19361184/5221149) – Andreas Apr 22 '19 at 15:55
  • As for the first question, I'm not following. Please edit the question and show example of what you mean. – Andreas Apr 22 '19 at 15:56
  • You might want to tag this question with `android` as it's somewhat specific to that platform? – stridecolossus Apr 22 '19 at 15:57
  • Thank you, both! It has been updaded. Andrea, thank you also for the article, basically I understand it as a general rule that "there is no recommended case for `System.gc()`". I'm not sure if there may be any exceptions. – ChrisZ Apr 22 '19 at 16:17
  • In the second variant, you are constructing a new `Foo` instance every time `bar()` is invoked, but on the other hand, it can get garbage collected afterwards. In the first variant, only one `Foo` instance is created, but it won’t get garbage collected, even when `bar()` is never called again. The question is, what are the costs for constructing a `Foo` instance. – Holger Apr 23 '19 at 16:00

0 Answers0