zoukankan      html  css  js  c++  java
  • 利用Instrument Leak来发现App中的内存泄露

    XCode提供了一组用于检测内存,调试动画,布局等的工具。对于调试一些性能问题,内存问题非常方便。这里我们使用Leak来发现代码中的内存泄露。

    在Leak中启动我们的应用开始监控:

    注意,在监控的时候有两种选择:All Heap Allocation,All Heap Allocation & Anonymous VM.这里我们只需要关心All Heap Allocation。因为这才是我们App真实使用的内存。Anonymous VM是操作系统在我们App启动的时候为进程预留的内存空间。它一般是大于App实际需要的内存大小的。并且这个大小我们也控制不了,因此监控没有意义。

    Focus on the heap allocations because your app has more control over heap allocations. Most of the memory allocations your app makes are heap allocations.

    The VM in anonymous VM stands for virtual memory. When your app launches, the operating system reserves a block of virtual memory for your application. This block is usually much larger than the amount of memory your app needs. When your app allocates memory, the operating system allocates the memory from the block it reserved.

    Remember the second sentence in the previous paragraph. The operating system determines the size of the virtual memory block, not your app. That’s why you should focus on the heap allocations instead of anonymous VM. Your app has no control over the size of the anonymous VM.

    Source: http://meandmark.com/blog/2014/01/instruments-heap-allocations-and-anonymous-vm/

    上面图中Instrument已经自动给我们标识出了一些有泄露的地方Leak Check那一栏中打红叉的位置。但是很多泄露还是发现不了。这些泄露需要借助下面所说的方法手工找出。

    对当前分配内存做标记

    我们可以通过Mark Generation来对当前内存做标记,每次标记Instrument会统计上次标记后新申请的内存,并会跟踪这些内存的使用(是否释放)。

    通过这个功能,我们就可以检测某些页面中存在的内存泄露情况。方法就是:

    1. 在进入某页面前,将内存做标记

    2. 进入页面,待内存稳定后,再次将内存做标记,这是标记列表中的对象都是当前页面所创建的。Instrument当然也会跟踪这些对象。

    3. 在页面中做些操作,然后退出页面。这是上一步中标记下来的应该大部分都会释放掉。剩下来的我们需要检查一下是否存在应该释放但是没有释放的。像一些UI元素如果界面退出还没有释放,说明存在内存泄露。下图就是某个页面退出后我对该页面创建时的内存标记:

    通过点击上面列表的每一个实例,我们可以看到每个实例完整的引用计数修改记录。如果是在我们写的代码中发生修改的话,我们还能看到代码。这样方便我们找出导致泄露的根源。

     

    上面的引用计数改变列表中,我们需要找出那种+1之后没有-1的记录(一般都是我们自己写的代码),然后找到对应的代码。我这里找的方法是:把这个列表拷贝到excel中,然后把所有非app代码的记录去掉,这样找会容易找到一点。(不知道为什么这里Instrument不提供筛选功能,不然会方便很多)

  • 相关阅读:
    Java study 1:The note of studying Socket which based UDP
    关于Meta标签中formatdetection属性及含义
    编辑sass报错:error style.scss (Line 3: Invalid GBK character "\xE5")解决办法
    比较三个 CSS 预处理器:Sass、LESS 和 Stylus(下)
    vue引入bootstrap、jquery
    Something about SeekingJobResume简历
    Something about SeekingJobTelInterview(电话面试)
    此时彼时
    The method getTextContent() is undefined for the type Node
    单例模式实现方式
  • 原文地址:https://www.cnblogs.com/Code-life/p/7767820.html
Copyright © 2011-2022 走看看