简体   繁体   English

Android:哪种方法最好调用垃圾收集器?

[英]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() ? 目前我在onStop()调用此方法,但最好在onDestroy()调用它吗?

It is never a good practice to call the GC manually. 手动调用GC绝不是一个好习惯。 Dalvik or ART simply knows better than us. Dalvik或ART只比我们更清楚。

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. 考虑一下调用System.gc()只是一个建议来启动在真正需要时运行的gc。

From javadoc: 来自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. 调用gc方法表明Java虚拟机花费了大量精力来回收未使用的对象,以使其当前占用的内存可用于快速重用。 When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects. 当控制从方法调用返回时,Java虚拟机已尽最大努力从所有丢弃的对象中回收空间。

Try to use your improvements to use less memory instead to call explicitly the gc (caching objects, using poolings and so on). 尝试使用您的改进来使用更少的内存,而不是显式调用gc(缓存对象,使用池等)。

It is not a good practice to call gc() directly in your activity(JVM knows when to run it). 在您的活动中直接调用gc()并不是一个好习惯(JVM知道何时运行它)。

If you are facing memory issues, try to find memory leaks in your app using MAT. 如果您遇到内存问题,请尝试使用MAT在应用程序中查找内存泄漏。

Also System.gc() call will not force a garbage collection.It is upto Dalvik to decide when to run gc System.gc()调用也不会强制进行垃圾收集。达尔维克决定何时运行gc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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