Flot2011
Flot2011

Reputation: 4671

Android - effective performance and memory management

I have a class MyClass which contains a large buffer, about 12Mb.

While my application is working, the instance of this class is constantly (50 times per second) updated.

What would be the most memory and performance wise way : to create a new object for each update and let the previous object to be garbage collected or to use the same object always? And, doesn't using the same object create a memory leak?

Or, in pseudo code:

is

MyClass object = new MyClass();
while(appIsRunning)
{
    if (getUpdatedObject(object))
       doSomething(object);
}

better than

while(appIsRunning)
{
    MyClass object = new MyClass();
    if (getUpdatedObject(object ))
       doSomething(object);
}

I am trying to make this question as common as possible, but I am ready to add any details if needed.

Upvotes: 1

Views: 81

Answers (1)

AterLux
AterLux

Reputation: 4654

Some java virtual machines, when creating small objects of known size, which is not viewed outside of it scope, creates object in stack, rather than in heap. For example oracle JVM after 7th version doing so. So it is may be more efficient to create small constant size temporary arrays inside.

But I don't know how VM in Android behave. And definitely, when your MyClass total size is large, it will be created in the heap anyway.

When object created in the heap, and no more references to it, it will be garbage collected, which means that all other objects will be checked and/or moved to free unused space. That requires CPU resources and slow down application.

So, when you creating new large object every time, it leads to quick memory usage, and often running garbage collector. That can dramatically slow down application execution and response.

On the other hand, when you are creating single object once outside, it not leads to garbage collection overhead, but it's whole memory remains occupied whole time, and cannot be garbage collected, even if object is not used in very instant moment.

Good compromise is to use WeakReference or SoftReference. It is containers of reference to the object, but they not prevent the object to be garbage collected. So, you can reuse your object, if it kept in memory, or create new one only in case if reference is lost

WeakReference just allows you to obtain reference to the object if it is not garbage collected yet.

SoftReference forces garbage collector to remain object intact, until there is no enough free space left in the heap.

Upvotes: 1

Related Questions