Question

I was wondering, I am using Application subclass to access some global data inside Activities. And I was wondering what would be better in terms off performance and memory.

Is it better to assign application object to field variable in onCreate and access it as a mamber

Activity

 onCreate() {
     mApp = (MyApplication) getApplication()
 }

or

Dont use a member and call getApplication every single time and assign it just to a local variable?

MyApplication app = (MyApplication) getApplication()

From my knowledge, local variables are allowed to be garbage collected right away but members have to be kept in memory.

Since I presume Application object is a big object, is it okay to keep it in memory or should I allow it to get garbage collected?

Thanks

Was it helpful?

Solution

The Application object would always be in memory. It's only its reference that you are either caching as a field member or retrieving it every time for a local variable. The latter doesn't give you any space or time benefits.


The Application object along with all of its children and grandchildren objects would live on heap only. All that the method getApplication() is doing is to return the address to the root of this object tree. The address/pointer/reference size would remain the same irrespective of how long the object tree or big each object element is.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top