iOS中内存自动释放池

自动释放池

iOS应用的主线程在每次runloop开始的时候创建自动释放池,在runloop结束的时候释放自动释放池。如果在一个runloop内,应用程序创建了大量临时对象,自动释放池可以减少内存峰值。

for (int i = 0; i < 1000000; i++) {
    
    

    NSString *string = [NSString stringWithFormat:@"hello world!"];
}

如果执行上面的代码,使用XCode可以看到有明显的短暂内存上涨。

for (int i = 0; i < 1000000; i++) {
    
    
    @autoreleasepool {
    
    
        NSString *string = [NSString stringWithFormat:@"hello world!"];
    }
}    

增加自动释放池以后,程序的内存占用没有明显的上涨,这个时候自动释放池释放了临时创建的变量内存。

自动释放池push和pop时机

autoreleasePool的push/pop和runloop有关。

在runloop进入kCFRunLoopEntry状态时,调用objc_autoreleasePoolPush方法

runloop进入kCFRunLoopBeforeWaiting状态时,调用objc_autoreleasePoolPop方法和objc_autoreleasePoolPush方法

runloop进入kCFRunLoopBeforeExit状态时,调用objc_autoreleasePoolPop方法。

自动释放池数据结构

struct AutoreleasePoolPageData
{
    
    
#if SUPPORT_AUTORELEASEPOOL_DEDUP_PTRS
    struct AutoreleasePoolEntry {
    
    
        uintptr_t ptr: 48;
        uintptr_t count: 16;

        static const uintptr_t maxCount = 65535; // 2^16 - 1
    };
    static_assert((AutoreleasePoolEntry){
    
     .ptr = OBJC_VM_MAX_ADDRESS }.ptr == OBJC_VM_MAX_ADDRESS, "OBJC_VM_MAX_ADDRESS doesn't fit into AutoreleasePoolEntry::ptr!");
#endif

	magic_t const magic;   //校验page是否完整
	__unsafe_unretained id *next;   //指向下一个存放数据的地址
	objc_thread_t const thread;     //当前线程
	AutoreleasePoolPage * const parent;  //父结点
	AutoreleasePoolPage *child;       //子结点
	uint32_t const depth;   //page深度
	uint32_t hiwat;   //最大入栈数量

	AutoreleasePoolPageData(__unsafe_unretained id* _next, objc_thread_t _thread, AutoreleasePoolPage* _parent, uint32_t _depth, uint32_t _hiwat)
		: magic(), next(_next), thread(_thread),
		  parent(_parent), child(nil),
		  depth(_depth), hiwat(_hiwat)
	{
    
    
	}
};

AutoreleasePoolPageData是AutoreleasePoolPage的基类。

扫描二维码关注公众号,回复: 15211607 查看本文章

自动释放池是双向链表的数据结构,parent指针指向父结点,child指向子结点,每页的数据大小是4096字节大小,每个页面是双向链表的一个结点。next代表的是当前页面可插入数据的位置。

自动释放池实现原理

push过程

void *
objc_autoreleasePoolPush(void)
{
    
    
    return AutoreleasePoolPage::push();
}

当代码中向自动释放池加入对象的时候,Objective-C内部会调用这个方法。

 static inline void *push() 
    {
    
    
        ReturnAutoreleaseInfo info = getReturnAutoreleaseInfo();
        moveTLSAutoreleaseToPool(info);

        id *dest;
        if (slowpath(DebugPoolAllocation)) {
    
    
            // Each autorelease pool starts on a new pool page.
            dest = autoreleaseNewPage(POOL_BOUNDARY);
        } else {
    
    
            dest = autoreleaseFast(POOL_BOUNDARY);
        }
        ASSERT(dest == (id *)EMPTY_POOL_PLACEHOLDER || *dest == POOL_BOUNDARY);
        return dest;
    }

这个方法主要是调用了autoreleaseFast方法。

 static inline id *autoreleaseFast(id obj)
    {
    
    
        AutoreleasePoolPage *page = hotPage();
        if (page && !page->full()) {
    
    
            return page->add(obj);
        } else if (page) {
    
    
            return autoreleaseFullPage(obj, page);
        } else {
    
    
            return autoreleaseNoPage(obj);
        }
    }

autoreleaseFast方法用于获取当前的hotPage,如果hotPage没有满直接插入数据,如果已经满了,重新分配一个page的空间然后插入,如果没有获取到page说明当前的自动释放池还没有初始化,需要初始化自动释放池。

id *add(id obj)
    {
    
    
        ASSERT(!full());
        unprotect();
        id *ret;

        ret = next;  // faster than `return next-1` because of aliasing
        *next++ = obj;

     done:
        protect();
        return ret;
    }

add方法精简后,可以看到add方法实际是把obj放入到next指针的位置,并把next++,函数的返回值是obj的存放地址。

static __attribute__((noinline))
    id *autoreleaseFullPage(id obj, AutoreleasePoolPage *page)
    {
    
    
        // The hot page is full. 
        // Step to the next non-full page, adding a new page if necessary.
        // Then add the object to that page.
        ASSERT(page == hotPage());
        ASSERT(page->full()  ||  DebugPoolAllocation);

        do {
    
    
            if (page->child) page = page->child;
            else page = new AutoreleasePoolPage(page);
        } while (page->full());

        setHotPage(page);
        return page->add(obj);
    }

autoreleaseFullPage函数是找到一个没有满的页面,调用add函数插入obj对象

static __attribute__((noinline))
    id *autoreleaseNoPage(id obj)
    {
    
    
        // "No page" could mean no pool has been pushed
        // or an empty placeholder pool has been pushed and has no contents yet
        ASSERT(!hotPage());

        bool pushExtraBoundary = false;
        if (haveEmptyPoolPlaceholder()) {
    
    
            // We are pushing a second pool over the empty placeholder pool
            // or pushing the first object into the empty placeholder pool.
            // Before doing that, push a pool boundary on behalf of the pool 
            // that is currently represented by the empty placeholder.
            pushExtraBoundary = true;
        }
        else if (obj != POOL_BOUNDARY  &&  DebugMissingPools) {
    
    
            // We are pushing an object with no pool in place, 
            // and no-pool debugging was requested by environment.
            _objc_inform("MISSING POOLS: (%p) Object %p of class %s "
                         "autoreleased with no pool in place - "
                         "just leaking - break on "
                         "objc_autoreleaseNoPool() to debug", 
                         objc_thread_self(), (void*)obj, object_getClassName(obj));
            objc_autoreleaseNoPool(obj);
            return nil;
        }
        else if (obj == POOL_BOUNDARY  &&  !DebugPoolAllocation) {
    
    
            // We are pushing a pool with no pool in place,
            // and alloc-per-pool debugging was not requested.
            // Install and return the empty pool placeholder.
            return setEmptyPoolPlaceholder();
        }

        

        // 初始化首页
        AutoreleasePoolPage *page = new AutoreleasePoolPage(nil);
        setHotPage(page);
        
        // 增加boundry标识
        if (pushExtraBoundary) {
    
    
            page->add(POOL_BOUNDARY);
        }
        
        // 添加obj
        return page->add(obj);
    }

如果当前没有自动释放池页面的时候,需要初始化AutoreleasePoolPage,然后调用add方法添加obj。这里setHotPage的作用是标识当前页面。

pop过程

void objc_autoreleasePoolPop(void *ctxt)
{
    
    
    AutoreleasePoolPage::pop(ctxt);
}

自动释放池在pop时会调用这个方法。

    static inline void
    pop(void *token)
    {
    
    
        // We may have an object in the ReturnAutorelease TLS when the pool is
        // otherwise empty. Release that first before checking for an empty pool
        // so we don't return prematurely. Loop in case the release placed a new
        // object in the TLS.
        while (releaseReturnAutoreleaseTLS())
            ;

        AutoreleasePoolPage *page;
        id *stop;
        if (token == (void*)EMPTY_POOL_PLACEHOLDER) {
    
    
            // 获取hotPage
            page = hotPage();
            if (!page) {
    
    
                // 自动释放池没有使用过,清空placeholder
                return setHotPage(nil);
            }
            // Pool was used. Pop its contents normally.
            // Pool pages remain allocated for re-use as usual.
            page = coldPage();
            token = page->begin();
        } else {
    
    
            page = pageForPointer(token);
        }

        stop = (id *)token;
        if (*stop != POOL_BOUNDARY) {
    
    
            if (stop == page->begin()  &&  !page->parent) {
    
    
                // Start of coldest page may correctly not be POOL_BOUNDARY:
                // 1. top-level pool is popped, leaving the cold page in place
                // 2. an object is autoreleased with no pool
            } else {
    
    
                
                return badPop(token);
            }
        }

        if (slowpath(PrintPoolHiwat || DebugPoolAllocation || DebugMissingPools)) {
    
    
            return popPageDebug(token, page, stop);
        }
        //清理自动释放池
        return popPage<false>(token, page, stop);
    }

在pop时会判断是否为EMPTY_POOL_PLACEHOLDER,POOL_BOUNDARY等标记。这个函数最后调用的popPage函数。

template<bool allowDebug>
    static void
    popPage(void *token, AutoreleasePoolPage *page, id *stop)
    {
    
    
        if (allowDebug && PrintPoolHiwat) printHiwat();
        //释放当前页面
        page->releaseUntil(stop);

        // memory: delete empty children
        if (allowDebug && DebugPoolAllocation  &&  page->empty()) {
    
    
            //debug使用
            // special case: delete everything during page-per-pool debugging
            AutoreleasePoolPage *parent = page->parent;
            page->kill();
            setHotPage(parent);
        } else if (allowDebug && DebugMissingPools  &&  page->empty()  &&  !page->parent) {
    
    
            // special case: delete everything for pop(top)
            // when debugging missing autorelease pools
            page->kill();
            setHotPage(nil);
        } else if (page->child) {
    
    
            // 如果页面实际占用空间小于一半,将child结点销毁
            if (page->lessThanHalfFull()) {
    
    
                page->child->kill();
            }
            如果页面实际占用空间大于一半,将child结点保留
            else if (page->child->child) {
    
    
                page->child->child->kill();
            }
        }
    }
    void releaseUntil(id *stop) 
    {
    
    
        // Not recursive: we don't want to blow out the stack 
        // if a thread accumulates a stupendous amount of garbage

        do {
    
    
            while (this->next != stop) {
    
    
             
                AutoreleasePoolPage *page = hotPage();

                while (page->empty()) {
    
    
                    page = page->parent;
                    setHotPage(page);
                }

                page->unprotect();
#if SUPPORT_AUTORELEASEPOOL_DEDUP_PTRS
                AutoreleasePoolEntry* entry = (AutoreleasePoolEntry*) --page->next;

                // create an obj with the zeroed out top byte and release that
                id obj = (id)entry->ptr;
                int count = (int)entry->count;  // grab these before memset
#else
                id obj = *--page->next;
#endif
                memset((void*)page->next, SCRIBBLE, sizeof(*page->next));
                page->protect();

                if (obj != POOL_BOUNDARY) {
    
    
#if SUPPORT_AUTORELEASEPOOL_DEDUP_PTRS
                    // release count+1 times since it is count of the additional
                    // autoreleases beyond the first one
                    for (int i = 0; i < count + 1; i++) {
    
    
                        objc_release(obj);
                    }
#else
                    objc_release(obj);
#endif
                }
            }

            // Stale return autorelease info is conceptually autoreleased. If
            // there is any, release the object in the info. If stale info is
            // present, we have to loop in case it autoreleased more objects
            // when it was released.
        } while (releaseReturnAutoreleaseTLS());

        setHotPage(this);

#if DEBUG
        // 检查子结点是否清空
        for (AutoreleasePoolPage *page = child; page; page = page->child) {
    
    
            ASSERT(page->empty());
        }
#endif
    }

releaseUntil函数会清空一个自动释放池,在释放对象的时候实际调用的是objc_release函数。

猜你喜欢

转载自blog.csdn.net/u011608357/article/details/128439012