Android: Which method is better to call the garbage collector in?

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

Here is my code:

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

      

I am currently onStop()

calling this method in , but is it better to call it internally onDestroy()

?

+3


source to share


3 answers


It's never a good idea to access the GC manually. Dalvik or ART just know better than us.

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



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

      

+1


source


Better to leave the garbage collector on its own.

When garbage collection needs to be collected, it starts.

Note that the call System.gc()

is only a suggestion to start gc, which works when really needed.



From the javadoc:

The gc method call assumes that the Java Virtual Machine is spending effort disposing of unused objects to make the memory they are currently available for quick reuse. When control returns from a method call, the Java Virtual Machine has made every effort to free up space from any discarded objects.

Try your enhancements to use less memory instead of explicitly calling gc (object caching, using pools, etc.).

0


source


It is not recommended to call gc()

directly in your activity (the JVM knows when to start it).

If you encounter memory problems, try to find memory leaks in your application using MAT.

Also calling System.gc () will not force garbage collection. It's up to Dalvik to decide when to run gc

0


source







All Articles