简体   繁体   中英

Android: In which method is better to call the Garbage Collector?

I am experiencing some out of memory issues on my app and want to call the garbage collector, but I am not sure in which method I should call it.

Here is my code:

 public static void CleanUpMemory(){
    System.runFinalization();
    Runtime.getRuntime().gc();
    System.gc();
 }

Currently I am calling this method in onStop() but is it better to call it inside onDestroy() ?

It is never a good practice to call the GC manually. Dalvik or ART simply knows better than us.

If your app requires a lot of memory to handle expensive operations, this is a good solution

<application
....
   android:largeHeap="true"> 

It is better to leave the garbage collector to work alone.

When it needs to garbage collect memory it starts.

Consider that the call System.gc() is only a suggest to start the gc that operates when it really necessary.

From javadoc:

Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.

Try to use your improvements to use less memory instead to call explicitly the gc (caching objects, using poolings and so on).

It is not a good practice to call gc() directly in your activity(JVM knows when to run it).

If you are facing memory issues, try to find memory leaks in your app using MAT.

Also System.gc() call will not force a garbage collection.It is upto Dalvik to decide when to run gc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM