Android GC 学习笔记

13 篇文章 0 订阅

阅读的文章:Android GC 原理探究

下面补充一些备注和笔记。

算法

复制算法 (Copying)图示:

这里写图片描述

标记-压缩算法 (Mark-Compact)英文描述:
mark-compact
总结起来就是 标记 —> 压缩有用的对象到一端 —> 回收此端外剩下的空间
图示:

这里写图片描述

可以看出,这两种算法都可以减少内存碎片

GC Roots

英文官方说明:


The root kinds are:

  • Class - class loaded by system class loader. Such classes can never be unloaded. They can hold objects via static fields. Please note that classes loaded by custom class loaders are not roots, unless corresponding instances of java.lang.Class happen to be roots of other kind(s).
  • Thread - live thread
  • Stack Local - local variable or parameter of Java method
  • JNI Local - local variable or parameter of JNI method
  • JNI Global - global JNI reference
  • Monitor Used - objects used as a monitor for synchronization
  • Held by JVM - objects held from garbage collection by JVM for its purposes. Actually the list of such objects depends on JVM implementation. Possible known cases are: the system class loader, a few important exception classes which the JVM knows about, a few pre-allocated objects for exception handling, and custom class loaders when they are in the process of loading classes. Unfortunately, JVM provides absolutely no additional detail for such objects. Thus it is up to the analyst to decide to which case a certain “Held by JVM” belongs.

If an object is a root, it is specially marked in all views showing individual objects.
中文

为什么GC会引起应用暂停(STW Stop The World)

因为gc需要确保标记准确无误,所以不可能一边标记,一边还有创建和销毁对象的活动,只能是暂定所有线程,等标记和清理完成后恢复所有线程。

弱引用(soft reference)

Android性能提升之强引用、软引用、弱引用、虚引用使用

可以应用到安卓开发中的tips

  • 我们首先要尽量避免掉频繁生成很多临时小变量(比如说:getView,onDraw等函数),以减少gc频率和内存碎片。
    另外,又要尽量去避免产生很多长生命周期的大对象,减少老年代执行gc的次数。 Old GC的速度一般会比Young gc慢10倍以上。并且执行”标记-压缩算法”,标记和压缩阶段都会暂停应用,造成较长时间的STW。

  • 也可以注册一个应用不可见(比如锁屏,被放到后台)的生命周期回调,主动触发gc, 因为反正应用不可见,GC 下以便之后运行更流畅,不过只是设想,还没实验。

  • 作者也说了,本来想故意“生成一些几百K的对象,试图去扩大可用堆大小的时候,反而会导致频繁的GC,因为这些对象的分配会导致GC,而GC后会让堆内存回到合适的比例,而我们使用的局部变量很快会被回收理论上存活对象还是那么多,我们的堆大小也会缩减回来无法达到扩充的目的”此路不通。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值