OC中的alloc到底是干了啥

1.問題引入

打印結(jié)果

從上圖看 p1 p2 p3 三個指針指向了同一塊內(nèi)存空間 0x600002acc6b0,由此可知在執(zhí)行alloc方法的時候已經(jīng)分配了內(nèi)存空間,init方法并沒有開辟新的內(nèi)存,下面看下alloc的底層是怎么實現(xiàn)的。

2.objc 源碼直接跑一哈(iOS_objc4-781版本)

工程配置參考

+ (id)alloc {
    return _objc_rootAlloc(self);
}
// Base class implementation of +alloc. cls is not nil.
// Calls [cls allocWithZone:nil].
id
_objc_rootAlloc(Class cls)
{
    return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}
static ALWAYS_INLINE id
callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
#if __OBJC2__
    if (slowpath(checkNil && !cls)) return nil;
    // 判斷是否有自定義的 allocWithZone 實現(xiàn)
    if (fastpath(!cls->ISA()->hasCustomAWZ())) {
        return _objc_rootAllocWithZone(cls, nil);
    }
#endif

    // No shortcuts available.
    if (allocWithZone) {
        return ((id(*)(id, SEL, struct _NSZone *))objc_msgSend)(cls, @selector(allocWithZone:), nil);
    }
    return ((id(*)(id, SEL))objc_msgSend)(cls, @selector(alloc));
}
  • fastpath slowpath
#define fastpath(x) (__builtin_expect(bool(x), 1))
#define slowpath(x) (__builtin_expect(bool(x), 0))

其實fastpathslowpath 就是告訴編譯器,boo(x) 最可能的結(jié)果為0 或者1,這樣寄存器讀取指令就默認優(yōu)先讀取YES或者NO部分的代碼,達到優(yōu)化目的。

  • hasCxxCtor hasCxxDtor 表示是否有c++類的創(chuàng)建和析構(gòu)方法。
  • fastpath(!cls->ISA()->hasCustomAWZ()) 這是判斷一個類是否有自定義的 +allocWithZone實現(xiàn)。
id
_objc_rootAllocWithZone(Class cls, malloc_zone_t *zone __unused)
{
    // allocWithZone under __OBJC2__ ignores the zone parameter
    //zone 參數(shù)不再使用 類創(chuàng)建實例內(nèi)存空間
    return _class_createInstanceFromZone(cls, 0, nil,
                                         OBJECT_CONSTRUCT_CALL_BADALLOC);
}
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)
{
    ASSERT(cls->isRealized()); 

    // 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;

    //計算需要開辟的內(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);
}
  • cls->instanceSize 流程
size_t instanceSize(size_t extraBytes) const {
    //編譯器快速計算內(nèi)存大小
    if (fastpath(cache.hasFastInstanceSize(extraBytes))) {
        return cache.fastInstanceSize(extraBytes);
    }
    
    // 計算類中所有屬性的大小 + 額外的字節(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;
}  
size_t fastInstanceSize(size_t extra) const
{
    ASSERT(hasFastInstanceSize(extra));

    //Gcc的內(nèi)建函數(shù) __builtin_constant_p 用于判斷一個值是否為編譯時常數(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個字節(jié)
        return align16(size + extra - FAST_CACHE_ALLOC_DELTA16);
    }
}

*align16 為16字節(jié)對齊算法

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

*alignedInstanceSize

uint32_t alignedInstanceSize() {
    return word_align(unalignedInstanceSize());
}
    
uint32_t unalignedInstanceSize() {
    assert(isRealized());
    return data()->ro->instanceSize;
}
    
static inline uint32_t word_align(uint32_t x) {
    return (x + WORD_MASK) & ~WORD_MASK;
}

#ifdef __LP64__
#   define WORD_MASK 7UL
#else
#   define WORD_MASK 3UL
#endif
  • alignedInstanceSizeisa指針大小,在64位架構(gòu)下為8字節(jié)大小,word_align里面為8字節(jié)對齊固定寫法,extraBytes為0,因為定義的CKPerson 沒有任何屬性,往下走有個最小返回 16的判斷,所以返回的size 為16。
  • calloc 分配內(nèi)存空間。
    obj0
  • initInstanceIsa 關(guān)聯(lián)isa。
    obj1

總結(jié)

經(jīng)過源碼分析alloc主要是做了開辟內(nèi)存空間的操作,核心方法為_class_createInstanceFromZone 計算---開辟----關(guān)聯(lián),總結(jié)圖如下。

alloc流程圖總結(jié)

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

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