alloc & init & new 底層源碼探索

理解對象的指針內(nèi)存地址的區(qū)別:

    LGPerson *p1 = [LGPerson alloc];
    LGPerson *p2 = [p1 init];
    LGPerson *p3 = [p1 init];
    LGNSLog(@"%@ - %p - %p",p1,p1,&p1);
    LGNSLog(@"%@ - %p - %p",p2,p2,&p2);
    LGNSLog(@"%@ - %p - %p",p3,p3,&p3);

下圖是輸出結(jié)果:分別輸出3個(gè)對象的內(nèi)容、指針地址、對象地址

指針和內(nèi)存地址

注: %p -> &p1:一個(gè)是內(nèi)存地址,
%p -> p1: 一個(gè)是指向內(nèi)存地址的指針

結(jié)論:通過上圖可以看出,alloc會為對象p1在內(nèi)存開辟空間,init則將p2,p3的指針指向p1的所在的內(nèi)存地址,3個(gè)對象指向的是同一個(gè)內(nèi)存空間,所以其內(nèi)容指針地址是相同的,但是對象的內(nèi)存地址是不同的,三個(gè)對象的內(nèi)存地址偏移8個(gè)字節(jié)

準(zhǔn)備工作:

  1. opensource上找到最新的OC源碼

    opensource

  2. 也可以直接在https://opensource.apple.com/tarballs上面查找最新的穩(wěn)定版本開源代碼。
    源碼直通車objc4-781 源碼

如何定位底層代碼執(zhí)行流程

  1. 下符號斷點(diǎn)的形式直接跟流程
  2. 通過摁住control - step into -> 符號斷點(diǎn)查看源碼出處
  3. 匯編查看跟流程->符號斷點(diǎn)查看源碼出處
匯編查看跟流程

[alloc init]流程

[alloc init]流程圖

其中:
核心方法中的cls->instanceSize先計(jì)算出需要的內(nèi)存空間大小->calloc向系統(tǒng)申請開辟內(nèi)存,返回地址指針->obj->initInstanceIsa關(guān)聯(lián)到相應(yīng)的類

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

    // No shortcuts available. // 沒有可用的編譯器優(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));
}

如上所示,在calloc方法中,當(dāng)我們無法確定實(shí)現(xiàn)走到哪步時(shí),可以通過斷點(diǎn)調(diào)試,判斷執(zhí)行走哪部分邏輯。這里是執(zhí)行到_objc_rootAllocWithZone

slowpath & fastpath

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

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

其中的__builtin_expect指令是由gcc引入的,
1、目的:編譯器可以對代碼進(jìn)行優(yōu)化,以減少指令跳轉(zhuǎn)帶來的性能下降。即性能優(yōu)化
2、作用:允許程序員將最有可能執(zhí)行的分支告訴編譯器。
3、指令的寫法為:__builtin_expect(EXP, N)。表示 EXP==N的概率很大。
4、fastpath定義中__builtin_expect((x),1)表示 x 的值為真的可能性更大;即 執(zhí)行if里面語句的機(jī)會更大
5、slowpath定義中的__builtin_expect((x),0)表示x 的值為假的可能性更大。即執(zhí)行else 里面語句的機(jī)會更大
6、在日常的開發(fā)中,也可以通過設(shè)置來優(yōu)化編譯器,達(dá)到性能優(yōu)化的目的,設(shè)置的路徑為:Build Setting --> Optimization Level --> Debug --> 將None 改為 fastest或者 smallest

cls->ISA()->hasCustomAWZ()

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

  1. 跳轉(zhuǎn)至_objc_rootAllocWithZone的源碼實(shí)現(xiàn)
id
_objc_rootAllocWithZone(Class cls, malloc_zone_t *zone __unused)// alloc 源碼 第四步
{
    // allocWithZone under __OBJC2__ ignores the zone parameter
    //zone 參數(shù)不再使用 類創(chuàng)建實(shí)例內(nèi)存空間
    return _class_createInstanceFromZone(cls, 0, nil,
                                         OBJECT_CONSTRUCT_CALL_BADALLOC);
}
  1. 跳轉(zhuǎn)至_class_createInstanceFromZone的源碼實(shí)現(xiàn),這部分是alloc源碼的核心操作,由下面的流程圖及源碼可知,該方法的實(shí)現(xiàn)主要分為三部分
  • cls->instanceSize:計(jì)算需要開辟的內(nèi)存空間大小
  • calloc申請內(nèi)存,返回地址指針
  • obj->initInstanceIsa:將 isa 關(guān)聯(lián)
static ALWAYS_INLINE id
_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
    //一次性讀取類的位信息以提高性能
    bool hasCxxCtor = cxxConstruct && cls->hasCxxCtor();
    bool hasCxxDtor = cls->hasCxxDtor();
    bool fast = cls->canAllocNonpointer();
    size_t size;

    //計(jì)算需要開辟的內(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 {
        //申請內(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類 與 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);
}
_class_createInstanceFromZone

instanceSize

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

  1. 跳轉(zhuǎn)至instanceSize的源碼實(shí)現(xiàn)
size_t instanceSize(size_t extraBytes) const {
    //編譯器快速計(jì)算內(nèi)存大小
    if (fastpath(cache.hasFastInstanceSize(extraBytes))) {
        return cache.fastInstanceSize(extraBytes);
    }
    
    // 計(jì)算類中所有屬性的大小 + 額外的字節(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;
}

通過斷點(diǎn)調(diào)試,會執(zhí)行到cache.fastInstanceSize方法,快速計(jì)算內(nèi)存大小

  1. 跳轉(zhuǎn)至fastInstanceSize的源碼實(shí)現(xiàn),通過斷點(diǎn)調(diào)試,會執(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);
    }
}
  1. 跳轉(zhuǎn)至align16的源碼實(shí)現(xiàn),這個(gè)方法是16字節(jié)對齊算法
//16字節(jié)對齊算法
static inline size_t align16(size_t x) {
    return (x + size_t(15)) & ~size_t(15);
}

[字節(jié)對齊](http://www.itdecent.cn/p/b06d99bfbba1

instanceSize流程

new

在開發(fā)中,初始化除了[alloc init],還可以使用new,兩者本質(zhì)上并沒有什么區(qū)別,以下是objc中new的源碼實(shí)現(xiàn),通過源碼可以得知,new函數(shù)中直接調(diào)用了callAlloc函數(shù)(即alloc中分析的函數(shù)),且調(diào)用了init函數(shù),所以可以得出new 其實(shí)就等價(jià)于 [alloc init]的結(jié)論

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

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

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

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