内存管理

作者: de7e01056dd4 | 来源:发表于2017-09-18 09:42 被阅读40次

    内存分类

    1. A dirty page is something that contains process specific information
    2. clean page is something that the kernel could regenerate later if needed such as rereading from disc.(在闪存中备份,能够再次读取
      So dirty pages are much more expensive than clean pages.
    • Clean Memory: 在闪存中有备份,能够再次读取。主要包括system framework、binary executable of your app、memory mapped files
    • Dirty Memory:所有非Clean Memory,系统无法回收。包括Heap allocation、caches、decompressed images

    terminology

    1. 段式虚拟内存
    2. 页式虚拟内存

    Clean Memory: 在闪存有备份,能再次读取重建
    Code, framework, memory-mapped files
    Dirty memory: 系统无法回收
    Heap allocations,decompressed images, caches

    • 降低内存峰值
    1. Lazy Allocation
    2. alloca(size_t)
      栈分配仅仅修改栈指针寄存器,比如malloc遍历并修改空闲列表要快的多
      仅仅适合于小
      3.calloc
      理解分配虚拟内存并设置清0标志位,但不分配物理内存
      4.NSAutoReleasePool
      基于引用计数,pool执行drain方法会release所有au
    • Objective-C将堆内存管理抽象出来了,不需要用malloc和free来分配或者释放对象所占内存。OC运行期环境把这部分工作抽象为一套内存管理架构,名叫引用计数

    引用计数

    • CFRunTime.c __CFDoExternRefOperation
    CF_EXPORT uintptr_t __CFDoExternRefOperation(uintptr_t op, id obj) {
        if (nil == obj) HALT;
        uintptr_t idx = EXTERN_TABLE_IDX(obj);
        uintptr_t disguised = DISGUISE(obj);
        CFLock_t *lock = &__NSRetainCounters[idx].lock;
        CFBasicHashRef table = __NSRetainCounters[idx].table; //取得对象对应的散列表
        uintptr_t count;
        switch (op) {
        case 300:   // increment
        case 350:   // increment, no event
            __CFLock(lock);
        CFBasicHashAddValue(table, disguised, disguised);
            __CFUnlock(lock);
            if (__CFOASafe && op != 350) __CFRecordAllocationEvent(__kCFObjectRetainedEvent, obj, 0, 0, NULL);
            return (uintptr_t)obj;
        case 400:   // decrement
            if (__CFOASafe) __CFRecordAllocationEvent(__kCFObjectReleasedEvent, obj, 0, 0, NULL);
        case 450:   // decrement, no event
            __CFLock(lock);
            count = (uintptr_t)CFBasicHashRemoveValue(table, disguised);
            __CFUnlock(lock);
            return 0 == count;
        case 500:
            __CFLock(lock);
            count = (uintptr_t)CFBasicHashGetCountOfKey(table, disguised);
            __CFUnlock(lock);
            return count;
        }
        return 0;
    }
    

    可以从__CFDoExternRefOperation 函数以及由此函数调用的各个函数名看出,苹果大概就是采用散列表(引用技术表)来管理引用计数

    通过散列表管理引用计数
    参考链接

    iOS内存管理及优化
    先弄清楚这里的学问,再来谈 iOS 内存管理与优化(一)

    相关文章

      网友评论

        本文标题:内存管理

        本文链接:https://www.haomeiwen.com/subject/dgwgjxtx.html