35.iOS底層學(xué)習(xí)之內(nèi)存管理自動(dòng)釋放池

本章提綱:
1、自動(dòng)釋放池的初識(shí)
2、自動(dòng)釋放池的數(shù)據(jù)結(jié)構(gòu)
3、自動(dòng)釋放池的源碼分析

1.自動(dòng)釋放池的初識(shí)

從main函數(shù)開始

main函數(shù)在iOS開發(fā)中,可以說(shuō)是一個(gè)非常不顯眼的存在,它隱藏在main.m文件中,是整個(gè)應(yīng)用程序的入口,有著非常重要的作用。我們常見到的main函數(shù)中的內(nèi)容如下:

image.png

可以看到幾行簡(jiǎn)短的代碼,其中@autoreleasepool就是我們今天要重點(diǎn)去探究的內(nèi)容,來(lái)看看@autoreleasepool到底是什么。我們通過兩種方式來(lái)研究下它的本質(zhì)。

  • Clang編譯查看
    我們通過命令
xcrun -sdk iphonesimulator clang -rewrite-objc main.m                           

生成相應(yīng)的.cpp文件,編譯完如下:

image.png

原來(lái)的@autoreleasepool被注釋掉了,隨之用__AtAutoreleasePool替代了,搜索下這個(gè)關(guān)鍵字,發(fā)現(xiàn)它的定義如下:

struct __AtAutoreleasePool {
  __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}
  ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}
  void * atautoreleasepoolobj;
};

這個(gè)定義其實(shí)是封裝了構(gòu)造函數(shù)和析構(gòu)函數(shù),舉個(gè)一樣的例子,我們定義一結(jié)構(gòu)體Lucky如下:

struct Lucky {
    Lucky(){
        printf("22222222\n");
    }
    
    ~Lucky(){
        printf("1111111");
    }
};

來(lái)看調(diào)試過程:


image.png

image.png

當(dāng)我們調(diào)用Lucky l;完畢后,打印22222222,當(dāng)我們出了作用域后,調(diào)用了析構(gòu)函數(shù)打印了1111111
這樣我們就能比較清楚的了解這個(gè)結(jié)構(gòu)體的定義,所以關(guān)鍵的方法是objc_autoreleasePoolPushobjc_autoreleasePoolPop。

  • 匯編開啟符號(hào)斷點(diǎn)查看
    另外一種方法,我們開啟符號(hào)斷點(diǎn),來(lái)進(jìn)行查看。
    image.png

    同樣可以定位到方法objc_autoreleasePoolPushobjc_autoreleasePoolPop,我們?cè)偬砑臃?hào)斷點(diǎn)objc_autoreleasePoolPush來(lái)看下該方法所屬的庫(kù)。
    image.png

    最終移步到庫(kù)libobjc.A.dylib,我們來(lái)進(jìn)一步的研究下它的數(shù)據(jù)結(jié)構(gòu)。

2.自動(dòng)釋放池的數(shù)據(jù)結(jié)構(gòu)

我們找到方法objc_autoreleasePoolPushobjc_autoreleasePoolPoplibobjc.A.dylib中定義:

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

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


void *
_objc_autoreleasePoolPush(void)
{
    return objc_autoreleasePoolPush();
}

void
_objc_autoreleasePoolPop(void *ctxt)
{
    objc_autoreleasePoolPop(ctxt);
}

最終分別調(diào)用的是AutoreleasePoolPage::push()AutoreleasePoolPage::pop(ctxt)。他們都是類AutoreleasePoolPage中的函數(shù),來(lái)看下類AutoreleasePoolPage的具體定義。

2.1 AutoreleasePoolPage的結(jié)構(gòu)

進(jìn)一步查看AutoreleasePoolPage的定義,發(fā)現(xiàn)他是繼承自AutoreleasePoolPageData

class AutoreleasePoolPage;
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 = MACH_VM_MAX_ADDRESS }.ptr == MACH_VM_MAX_ADDRESS, "MACH_VM_MAX_ADDRESS doesn't fit into AutoreleasePoolEntry::ptr!");
#endif

    magic_t const magic; // 16
    __unsafe_unretained id *next; // 8
    pthread_t const thread; // 8
    //父節(jié)點(diǎn)
    AutoreleasePoolPage * const parent; // 8
    //子節(jié)點(diǎn)
    AutoreleasePoolPage *child; // 8
    
    uint32_t const depth; // 4
    uint32_t hiwat;  // 4

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

可以了解到AutoreleasePoolPageData是一個(gè)雙向鏈表結(jié)構(gòu),我們從對(duì)于AutoreleasePoolPage的實(shí)現(xiàn)的注釋

/***********************************************************************
Autorelease pool implementation
A thread's autorelease pool is a stack of pointers.
Each pointer is either an object to release, or POOL_BOUNDARY which is
an autorelease pool boundary.
A pool token is a pointer to the POOL_BOUNDARY for that pool. When
the pool is popped, every object hotter than the sentinel is released.
The stack is divided into a doubly-linked list of pages. Pages are added
and deleted as necessary.
Thread-local storage points to the hot page, where newly autoreleased
objects are stored.
**********************************************************************/

大致翻譯:
自動(dòng)釋放池的實(shí)現(xiàn)
一個(gè)線程的自動(dòng)釋放池是一堆指針。
每個(gè)指針要么是要釋放的對(duì)象,要么是哨兵指針,自動(dòng)釋放池的邊界。
一個(gè)釋放池會(huì)有一個(gè)指針指向自動(dòng)釋放池的邊界。當(dāng)池子被出棧時(shí),此時(shí)池子中的每個(gè)對(duì)象都比哨兵對(duì)象更‘熱’。
這個(gè)棧被分成了雙向鏈接的頁(yè)面列表。頁(yè)面在必要的時(shí)候可以被添加或者被刪除。
線程本地存儲(chǔ)指針指向新創(chuàng)建的存儲(chǔ)對(duì)象的自動(dòng)釋放池。

AutoreleasePoolPageData中有幾個(gè)成員:

  • magic_t const magic:用來(lái)校驗(yàn)AutoreleasePoolPage結(jié)構(gòu)是否完整;
  • __unsafe_unretained id *next :指向最新添加的autoreleased對(duì)象的下一個(gè)位置,初始化時(shí)指向begin;
  • pthread_t const thread :保存當(dāng)前頁(yè)所在的線程;
  • AutoreleasePoolPage * const parent :指向父結(jié)點(diǎn),第一個(gè)AutoreleasePoolPage結(jié)點(diǎn)的父結(jié)點(diǎn)為nil;
  • AutoreleasePoolPage *child :指向子結(jié)點(diǎn),最后一個(gè)AutoreleasePoolPage結(jié)點(diǎn)的子結(jié)點(diǎn)為nil;
  • uint32_t const depth:當(dāng)前結(jié)點(diǎn)的深度,從0開始,往后遞增;
  • uint32_t hiwat :代表hige water mark最大入棧數(shù)量標(biāo)記;

通過注釋和結(jié)構(gòu)我們了解到,每個(gè)page本身是一個(gè)棧結(jié)構(gòu),而pagepage之間又是雙向鏈接的,是雙向鏈表結(jié)構(gòu),每一頁(yè)的大小是4096(4k)。

3.自動(dòng)釋放池的源碼分析

3.1自動(dòng)釋放池的壓棧

前邊分析到方法_objc_autoreleasePoolPush,它的實(shí)際實(shí)現(xiàn)最終找到AutoreleasePoolPage::push(),push方法的具體實(shí)現(xiàn)如下:

  static inline void *push() 
    {
        id *dest;
        if (slowpath(DebugPoolAllocation)) {
            //需要?jiǎng)?chuàng)建新頁(yè)
            // Each autorelease pool starts on a new pool page.
            dest = autoreleaseNewPage(POOL_BOUNDARY);
        } else {
            //不用創(chuàng)建新頁(yè)
            dest = autoreleaseFast(POOL_BOUNDARY);
        }
        ASSERT(dest == EMPTY_POOL_PLACEHOLDER || *dest == POOL_BOUNDARY);
        return dest;
    }

這里根據(jù)是否創(chuàng)建新頁(yè)分出兩個(gè)方法,需要?jiǎng)?chuàng)建新頁(yè)autoreleaseNewPage(POOL_BOUNDARY);
不需要?jiǎng)?chuàng)建,也就是當(dāng)前頁(yè)沒滿,調(diào)用autoreleaseFast(POOL_BOUNDARY)。

  • 創(chuàng)建新頁(yè)autoreleaseNewPage
    它的實(shí)現(xiàn)如下:
    id *autoreleaseNewPage(id obj)
    {
        AutoreleasePoolPage *page = hotPage();
        if (page) return autoreleaseFullPage(obj, page);
        else return autoreleaseNoPage(obj);
    }

創(chuàng)建新界面中又有兩個(gè)分支:一個(gè)是autoreleaseFullPage當(dāng)前頁(yè)滿了的情況;
另外一個(gè)是autoreleaseNoPage還沒創(chuàng)建頁(yè)的情況。

  • 方法hotPage()
    image.png

    方法tls_get_direct中的具體操作對(duì)真機(jī)和模擬器進(jìn)行了區(qū)分,hotPage存在了TLS中,真機(jī)的情況下通過方法_os_tsd_get_direct進(jìn)行讀取。

EMPTY_POOL_PLACEHOLDER是有注釋的,它是一個(gè)什么樣的狀態(tài)下會(huì)返回nil呢?注釋是這樣解釋的:

// EMPTY_POOL_PLACEHOLDER is stored in TLS when exactly one pool is
// pushed and it has never contained any objects. This saves memory
// when the top level (i.e. libdispatch) pushes and pops pools but
// never uses them.
# define EMPTY_POOL_PLACEHOLDER ((id*)1)

EMPTY_POOL_PLACEHOLDER是一個(gè)宏定義,它的注釋是:
EMPTY_POOL_PLACEHOLDER是存儲(chǔ)在TLS中當(dāng)恰巧一個(gè)池子被入?;蛘叱鰲?,并且這個(gè)池子不含有對(duì)象。這樣做會(huì)節(jié)省內(nèi)存,當(dāng)棧頂對(duì)象壓入或者彈出池子,但是從來(lái)也沒有被使用過。

  • 方法autoreleaseFullPage
    image.png
  • 方法autoreleaseNoPage
    image.png

    以上兩個(gè)方法都包含了方法添加對(duì)象到當(dāng)前頁(yè)中add方法,來(lái)看下它的具體實(shí)現(xiàn):
    image.png

    add方法首先確保非滿狀態(tài),然后把obj添加到next的位置。
    以上走的是創(chuàng)建新頁(yè)autoreleaseNewPage的流程,接下來(lái)看autoreleaseFast的流程:
   static inline id *autoreleaseFast(id obj)
    {
        AutoreleasePoolPage *page = hotPage();
        //page沒滿 直接調(diào)用add 把obj添加到next指向的位置
        if (page && !page->full()) {
            return page->add(obj);
        } else if (page) {
            //page存在 但是已經(jīng)滿了 開辟新頁(yè) 并把對(duì)象存到新的page中
            return autoreleaseFullPage(obj, page);
        } else {
            //還沒創(chuàng)建過新頁(yè) 創(chuàng)建新頁(yè) 并把對(duì)象obj存進(jìn)去
            return autoreleaseNoPage(obj);
        }
    }

以上就是obj入棧的過程,主要通過三個(gè)函數(shù)去處理autoreleaseFullPageautoreleaseNoPage還有add。分別對(duì)應(yīng)對(duì)象插入到新的位置時(shí)的三種情況:
1、如果有正好的位置next,那么直接把對(duì)象objadd進(jìn)去;
2、如果當(dāng)前頁(yè)已經(jīng)滿了,那么去走autoreleaseFullPage,也就是開辟新頁(yè),把新頁(yè)和前一頁(yè)進(jìn)行關(guān)聯(lián),把next位置更新一下,把對(duì)象存的新開辟的新頁(yè)中;
3、如果當(dāng)前還沒創(chuàng)建頁(yè),那么就創(chuàng)建一個(gè)首頁(yè),并把要存的對(duì)象存進(jìn)去;

3.2自動(dòng)釋放池的出棧

出棧的關(guān)鍵方法是:objc_autoreleasePoolPop,最終找到的方法是AutoreleasePoolPage::pop(ctxt)pop的源碼如下:

  static inline void
    pop(void *token)
    {
        AutoreleasePoolPage *page;
        id *stop;
        //棧頂?shù)膒ool未被使用
        if (token == (void*)EMPTY_POOL_PLACEHOLDER) {
            // Popping the top-level placeholder pool.
            //彈出棧頂指針
            page = hotPage();
            if (!page) {
                //這個(gè)pool沒有被使用過 清空
                // Pool was never used. Clear the placeholder.
                return setHotPage(nil);
            }
            //如果Pool已經(jīng)被使用,那么正常彈出它的內(nèi)容
            // Pool was used. Pop its contents normally.
            //保留pool pages為了再使用
            // Pool pages remain allocated for re-use as usual.
            //拿到hotPage然后往前遍歷 拿到最前邊的父節(jié)點(diǎn)
            page = coldPage();
            token = page->begin();
        } else {
            //通過地址找到對(duì)應(yīng)的頁(yè) p/size 每頁(yè)4k 2的12次方 2的十次方乘以4 4k
            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
                //存在自動(dòng)釋放池的第一個(gè)節(jié)點(diǎn)存儲(chǔ)的第一個(gè)對(duì)象不是邊界符的情況, 有兩種情況導(dǎo)致:
                //1.頂層池沒釋放, 但留下了第一個(gè)節(jié)點(diǎn)
                //2.沒有自動(dòng)釋放池的 autorelease 對(duì)象
                
            } else {
                // Error. For bincompat purposes this is not 
                // fatal in executables built with old SDKs.
                //報(bào)錯(cuò)
                return badPop(token);
            }
        }

        if (slowpath(PrintPoolHiwat || DebugPoolAllocation || DebugMissingPools)) {
            return popPageDebug(token, page, stop);
        }

        return popPage<false>(token, page, stop);
    }

此方法中真正釋放對(duì)象的方法是popPage。

 popPage(void *token, AutoreleasePoolPage *page, id *stop)
    {
        if (allowDebug && PrintPoolHiwat) printHiwat();

        //遍歷當(dāng)前頁(yè) 直到為stop的位置 跳出遍歷
        page->releaseUntil(stop);

        // memory: delete empty children
        if (allowDebug && DebugPoolAllocation  &&  page->empty()) {
            // special case: delete everything during page-per-pool debugging
            //刪除空頁(yè) kill內(nèi)部是do-while循環(huán) 向父節(jié)點(diǎn)的方向遍歷并把前一個(gè)節(jié)點(diǎn)置空
            AutoreleasePoolPage *parent = page->parent;
            page->kill();
            setHotPage(parent);
            //當(dāng)前page為空 但是前一頁(yè)不為空 那么全部刪除
        } else if (allowDebug && DebugMissingPools  &&  page->empty()  &&  !page->parent) {
            // special case: delete everything for pop(top)
            // when debugging missing autorelease pools
            page->kill();
            setHotPage(nil);
            //page有子節(jié)點(diǎn)
        } else if (page->child) {
            //有一半是空的 子節(jié)點(diǎn)存在 那么從子節(jié)點(diǎn)開始刪除
            // hysteresis: keep one empty child if page is more than half full
            if (page->lessThanHalfFull()) {
                page->child->kill();
            }
            //否則去查下子節(jié)點(diǎn)的子節(jié)點(diǎn) 開始清空
            else if (page->child->child) {
                page->child->child->kill();
            }
        }
    }

其中kill方法主要是一個(gè)do-while循環(huán),從后往前遍歷父節(jié)點(diǎn),父節(jié)點(diǎn)存在把后一節(jié)點(diǎn)刪除,這樣一個(gè)一個(gè)移除。

而方法releaseUntil(stop);是釋放對(duì)象的關(guān)鍵方法。

    void releaseUntil(id *stop) 
    {
        // Not recursive: we don't want to blow out the stack 
        // if a thread accumulates a stupendous amount of garbage
        
        while (this->next != stop) {// 一直循環(huán)到 next 指針指向 stop 為止
            // Restart from hotPage() every time, in case -release 
            // autoreleased more objects
            AutoreleasePoolPage *page = hotPage();

            // fixme I think this `while` can be `if`, but I can't prove it
            while (page->empty()) { //向前查找 找到第一個(gè)不為空的page
                page = page->parent;
                setHotPage(page);
            }

            page->unprotect();

            id obj = *--page->next; // 先將 next 指針向前移位, 然后再取出移位后地址中的值
            memset((void*)page->next, SCRIBBLE, sizeof(*page->next));
            page->protect();

            if (obj != POOL_BOUNDARY) {

                objc_release(obj);//進(jìn)行一次release釋放
            }
        }

對(duì)拿到的stop的節(jié)點(diǎn)之前進(jìn)行遍歷,并釋放對(duì)象。

實(shí)例擴(kuò)展

之前在項(xiàng)目中使用過自動(dòng)釋放池降低內(nèi)存峰值。如果在短時(shí)間內(nèi)創(chuàng)建大量的臨時(shí)變量,那么會(huì)導(dǎo)致內(nèi)存峰值增大,使用自動(dòng)釋放池可以有效的降低峰值。原因是自己創(chuàng)建個(gè)池子大量的臨時(shí)變量就在自己的池子里了,而不是線程的主池里。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容