不用但一定要懂 ---- iOS 之 alloc&init 原理

首先來(lái)一張圖,看下alloc 做了些什么:

然后我們來(lái)跟進(jìn)一下源碼

1、進(jìn)入alloc方法的源碼實(shí)現(xiàn)
//alloc源碼分析-第一步
+ (id)alloc {
    return _objc_rootAlloc(self);
}
2、_objc_rootAlloc的源碼實(shí)現(xiàn)
//alloc源碼分析-第二步
id
_objc_rootAlloc(Class cls)
{
    return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}
3、 callAlloc的源碼實(shí)現(xiàn)
static ALWAYS_INLINE id
callAlloc(Class cls, bool checkNil, bool allocWithZone=false)// alloc 源碼 第三步
{
#if __OBJC2__ //有可用的編譯器優(yōu)化
    /*
     參考鏈接:http://m.itdecent.cn/p/536824702ab6
     */
    
    // checkNil 為false,!cls 也為false ,所以slowpath 為 false,假值判斷不會(huì)走到if里面,即不會(huì)返回nil
    if (slowpath(checkNil && !cls)) return nil;
    
    //判斷一個(gè)類(lèi)是否有自定義的 +allocWithZone 實(shí)現(xiàn),沒(méi)有則走到if里面的實(shí)現(xiàn)
    if (fastpath(!cls->ISA()->hasCustomAWZ())) {
        return _objc_rootAllocWithZone(cls, nil);
    }
#endif

    // No shortcuts available. // 沒(méi)有可用的編譯器優(yōu)化
    if (allocWithZone) {
        return ((id(*)(id, SEL, struct _NSZone *))objc_msgSend)(cls, @selector(allocWithZone:), nil);
    }
    return ((id(*)(id, SEL))objc_msgSend)(cls, @selector(alloc));
}

其中關(guān)于slowpathfastpath這里需要簡(jiǎn)要說(shuō)明下,這兩個(gè)都是objc源碼中定義的宏,其定義如下

//x很可能為真, fastpath 可以簡(jiǎn)稱(chēng)為 真值判斷
#define fastpath(x) (__builtin_expect(bool(x), 1)) 
//x很可能為假,slowpath 可以簡(jiǎn)稱(chēng)為 假值判斷
#define slowpath(x) (__builtin_expect(bool(x), 0)) 

其中的__builtin_expect指令是由gcc引入的

  • 目的:編譯器可以對(duì)代碼進(jìn)行優(yōu)化,以減少指令跳轉(zhuǎn)帶來(lái)的性能下降。即性能優(yōu)化
  • 作用:允許程序員將最有可能執(zhí)行的分支告訴編譯器。
  • 指令的寫(xiě)法為:__builtin_expect(EXP, N)。表示 EXP==N的概率很大。
  • fastpath定義中__builtin_expect((x),1)表示 x 的值為真的可能性更大;即 執(zhí)行if 里面語(yǔ)句的機(jī)會(huì)更大
  • slowpath定義中的__builtin_expect((x),0)表示 x 的值為假的可能性更大。即執(zhí)行 else 里面語(yǔ)句的機(jī)會(huì)更大

cls->ISA()->hasCustomAWZ()
其中fastpath中的 cls->ISA()->hasCustomAWZ() 表示判斷一個(gè)類(lèi)是否有自定義的+allocWithZone 實(shí)現(xiàn),這里通過(guò)斷點(diǎn)調(diào)試,是沒(méi)有自定義的實(shí)現(xiàn),所以會(huì)執(zhí)行到 if 里面的代碼,即走到_objc_rootAllocWithZone

4、_objc_rootAllocWithZone的源碼實(shí)現(xiàn)
{
    // allocWithZone under __OBJC2__ ignores the zone parameter
    //zone 參數(shù)不再使用 類(lèi)創(chuàng)建實(shí)例內(nèi)存空間
    return _class_createInstanceFromZone(cls, 0, nil,
                                         OBJECT_CONSTRUCT_CALL_BADALLOC);
}

5、_class_createInstanceFromZone的源碼實(shí)現(xiàn),這部分是alloc源碼的核心操作,由下面的流程圖及源碼可知,該方法的實(shí)現(xiàn)主要分為三部分

  • cls->instanceSize:計(jì)算需要開(kāi)辟的內(nèi)存空間大小
  • calloc:申請(qǐng)內(nèi)存,返回地址指針
  • obj->initInstanceIsa:將類(lèi)與isa關(guān)聯(lián)
_class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone,
                              int construct_flags = OBJECT_CONSTRUCT_NONE,
                              bool cxxConstruct = true,
                              size_t *outAllocatedSize = nil)// alloc 源碼 第五步
{
    ASSERT(cls->isRealized()); //檢查是否已經(jīng)實(shí)現(xiàn)

    // Read class's info bits all at once for performance
    //一次性讀取類(lèi)的位信息以提高性能
    bool hasCxxCtor = cxxConstruct && cls->hasCxxCtor();
    bool hasCxxDtor = cls->hasCxxDtor();
    bool fast = cls->canAllocNonpointer();
    size_t size;

    //計(jì)算需要開(kāi)辟的內(nèi)存大小,傳入的extraBytes 為 0
    size = cls->instanceSize(extraBytes);
    if (outAllocatedSize) *outAllocatedSize = size;

    id obj;
    if (zone) {
        obj = (id)malloc_zone_calloc((malloc_zone_t *)zone, 1, size);
    } else {
        //申請(qǐng)內(nèi)存
        obj = (id)calloc(1, size);
    }
    if (slowpath(!obj)) {
        if (construct_flags & OBJECT_CONSTRUCT_CALL_BADALLOC) {
            return _objc_callBadAllocHandler(cls);
        }
        return nil;
    }

    if (!zone && fast) {
        //將 cls類(lèi) 與 obj指針(即isa) 關(guān)聯(lián)
        obj->initInstanceIsa(cls, hasCxxDtor);
    } else {
        // Use raw pointer isa on the assumption that they might be
        // doing something weird with the zone or RR.
        obj->initIsa(cls);
    }

    if (fastpath(!hasCxxCtor)) {
        return obj;
    }

    construct_flags |= OBJECT_CONSTRUCT_FREE_ONFAILURE;
    return object_cxxConstructFromClass(obj, cls, construct_flags);
}

alloc :分配內(nèi)存、關(guān)聯(lián)指針

  • cls->instanceSize:計(jì)算所需內(nèi)存大小

計(jì)算需要開(kāi)辟內(nèi)存的大小的執(zhí)行流程如下所示

1、instanceSize的源碼實(shí)現(xiàn)

size_t instanceSize(size_t extraBytes) const {
    //編譯器快速計(jì)算內(nèi)存大小
    if (fastpath(cache.hasFastInstanceSize(extraBytes))) {
        return cache.fastInstanceSize(extraBytes);
    }
    
    // 計(jì)算類(lèi)中所有屬性的大小 + 額外的字節(jié)數(shù)0
    size_t size = alignedInstanceSize() + extraBytes;
    // CF requires all objects be at least 16 bytes.
    //如果size 小于 16,最小取16
    if (size < 16) size = 16;
    return size;
}

2、fastInstanceSize的源碼實(shí)現(xiàn),會(huì)執(zhí)行到align16

size_t fastInstanceSize(size_t extra) const
{
    ASSERT(hasFastInstanceSize(extra));

    //Gcc的內(nèi)建函數(shù) __builtin_constant_p 用于判斷一個(gè)值是否為編譯時(shí)常數(shù),如果參數(shù)EXP 的值是常數(shù),函數(shù)返回 1,否則返回 0
    if (__builtin_constant_p(extra) && extra == 0) {
        return _flags & FAST_CACHE_ALLOC_MASK16;
    } else {
        size_t size = _flags & FAST_CACHE_ALLOC_MASK;
        // remove the FAST_CACHE_ALLOC_DELTA16 that was added
        // by setFastInstanceSize
        //刪除由setFastInstanceSize添加的FAST_CACHE_ALLOC_DELTA16 8個(gè)字節(jié)
        return align16(size + extra - FAST_CACHE_ALLOC_DELTA16);
    }
}

3、align16的這個(gè)方法是16字節(jié)對(duì)齊算法

//16字節(jié)對(duì)齊算法
static inline size_t align16(size_t x) {
    return (x + size_t(15)) & ~size_t(15);
}

init 源碼探索

init的源碼實(shí)現(xiàn)有以下兩種

1、類(lèi)方法 init
+ (id)init {
    return (id)self;
}
2、實(shí)例方法 init
- (id)init {
    return _objc_rootInit(self);
}

_objc_rootInit的源碼實(shí)現(xiàn)

id
_objc_rootInit(id obj)
{
    // In practice, it will be hard to rely on this function.
    // Many classes do not properly chain -init calls.
    return obj;
}

有上述代碼可以,都是的是傳入的self本身。


new 源碼探索

+ (id)new {
    return [callAlloc(self, false/*checkNil*/) init];
}

通過(guò)源碼可以得知,new函數(shù)中直接調(diào)用了callAlloc函數(shù)(即alloc中分析的函數(shù)),且調(diào)用了init函數(shù),所以可以得出new 其實(shí)就等價(jià)于 [alloc init]的結(jié)論

但是一般開(kāi)發(fā)中并不建議使用new,主要是因?yàn)橛袝r(shí)會(huì)重寫(xiě)init方法做一些自定義的操作,用new初始化可能會(huì)無(wú)法走到自定義的部分。


總結(jié):

1、 通過(guò)對(duì)alloc源碼的分析,可以得知alloc的主要目的就是開(kāi)辟內(nèi)存,而且開(kāi)辟的內(nèi)存需要使用16字節(jié)對(duì)齊算法,現(xiàn)在開(kāi)辟的內(nèi)存的大小基本上都是16的整數(shù)倍
開(kāi)辟內(nèi)存的核心步驟有3步:計(jì)算 -- 申請(qǐng) -- 關(guān)聯(lián)。
2、對(duì)init的源碼分析,可得知 直接返回了obj,里面什么也沒(méi)有做,而我們自定義一個(gè)對(duì)象,定義他的屬性,在它初始化的時(shí)候,它就有一些默認(rèn)值,比如,占位圖、占位字符,我們需要重寫(xiě)init方法,在它的初始化方法中,給這些屬性賦值,這就是init的作用。
3 、而 new 則是對(duì) allocinit 的簡(jiǎn)寫(xiě)形式而已,但是一般開(kāi)發(fā)中并不建議使用new,主要是因?yàn)橛袝r(shí)會(huì)重寫(xiě)init方法做一些自定義的操作,用new初始化可能會(huì)無(wú)法走到自定義的部分。

最后編輯于
?著作權(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)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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