0

I have two questions regarding Android memory optimization:

  1. Which is more memory expensive in Android, to use a global field or local field?
  2. Dependency injection with dagger- is it better to use objects (services, view models.. ) in an @applicationScope or @activityScope
Brandon Minnick
  • 13,342
  • 15
  • 65
  • 123
S qasem
  • 273
  • 1
  • 8
  • Have you tried a little research. SO is not well suited for these sorts of questions. Question #1 makes me cringe; don't allow premature optimization drive using class vs local objects. Use the right scope for the right reason. The second might be best answered by reading things like https://stackoverflow.com/q/41842493/1531971 –  Apr 18 '18 at 20:30

1 Answers1

0

Local variables are stored on the stack and when the function is finished, the local variables are gone as well. Global variables always exist and use their memory during the life time of the entire program. Its always better to declare a variable nearest to where it's used. So local variables are to be preferred.

About dagger 2 custom scope, the instances scoped in @ApplicationScope lives as long as Application object and @ActivityScope keeps references as long as Activity exists. So the objects should be under the scopes in which it is required. If it is required only in the activity or its hosted fragments use @ActivityScope or if you need the singleton object in an application scope define it @ApplicationScope.

Hope this helped you.

Telvin Mathew
  • 345
  • 1
  • 3
  • 10