美文网首页
不用但一定要懂 ---- iOS 之 alloc&init 原理

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

作者: 我来也super | 来源:发表于2022-06-01 10:37 被阅读0次

    首先来一张图,看下alloc 做了些什么:

    然后我们来跟进一下源码

    1、进入alloc方法的源码实现
    //alloc源码分析-第一步
    + (id)alloc {
        return _objc_rootAlloc(self);
    }
    
    2、_objc_rootAlloc的源码实现
    //alloc源码分析-第二步
    id
    _objc_rootAlloc(Class cls)
    {
        return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
    }
    
    3、 callAlloc的源码实现
    static ALWAYS_INLINE id
    callAlloc(Class cls, bool checkNil, bool allocWithZone=false)// alloc 源码 第三步
    {
    #if __OBJC2__ //有可用的编译器优化
        /*
         参考链接:https://www.jianshu.com/p/536824702ab6
         */
        
        // checkNil 为false,!cls 也为false ,所以slowpath 为 false,假值判断不会走到if里面,即不会返回nil
        if (slowpath(checkNil && !cls)) return nil;
        
        //判断一个类是否有自定义的 +allocWithZone 实现,没有则走到if里面的实现
        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));
    }
    

    其中关于slowpathfastpath这里需要简要说明下,这两个都是objc源码中定义的宏,其定义如下

    //x很可能为真, fastpath 可以简称为 真值判断
    #define fastpath(x) (__builtin_expect(bool(x), 1)) 
    //x很可能为假,slowpath 可以简称为 假值判断
    #define slowpath(x) (__builtin_expect(bool(x), 0)) 
    

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

    • 目的:编译器可以对代码进行优化,以减少指令跳转带来的性能下降。即性能优化
    • 作用:允许程序员将最有可能执行的分支告诉编译器。
    • 指令的写法为:__builtin_expect(EXP, N)。表示 EXP==N的概率很大。
    • fastpath定义中__builtin_expect((x),1)表示 x 的值为真的可能性更大;即 执行if 里面语句的机会更大
    • slowpath定义中的__builtin_expect((x),0)表示 x 的值为假的可能性更大。即执行 else 里面语句的机会更大

    cls->ISA()->hasCustomAWZ()
    其中fastpath中的 cls->ISA()->hasCustomAWZ() 表示判断一个类是否有自定义的+allocWithZone 实现,这里通过断点调试,是没有自定义的实现,所以会执行到 if 里面的代码,即走到_objc_rootAllocWithZone

    4、_objc_rootAllocWithZone的源码实现
    {
        // allocWithZone under __OBJC2__ ignores the zone parameter
        //zone 参数不再使用 类创建实例内存空间
        return _class_createInstanceFromZone(cls, 0, nil,
                                             OBJECT_CONSTRUCT_CALL_BADALLOC);
    }
    

    5、_class_createInstanceFromZone的源码实现,这部分是alloc源码的核心操作,由下面的流程图及源码可知,该方法的实现主要分为三部分

    • cls->instanceSize:计算需要开辟的内存空间大小
    • calloc:申请内存,返回地址指针
    • obj->initInstanceIsa:将类与isa关联
    _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()); //检查是否已经实现
    
        // 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;
    
        //计算需要开辟的内存大小,传入的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 {
            //申请内存
            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) 关联
            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 :分配内存、关联指针

    • cls->instanceSize:计算所需内存大小

    计算需要开辟内存的大小的执行流程如下所示

    1、instanceSize的源码实现

    size_t instanceSize(size_t extraBytes) const {
        //编译器快速计算内存大小
        if (fastpath(cache.hasFastInstanceSize(extraBytes))) {
            return cache.fastInstanceSize(extraBytes);
        }
        
        // 计算类中所有属性的大小 + 额外的字节数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的源码实现,会执行到align16

    size_t fastInstanceSize(size_t extra) const
    {
        ASSERT(hasFastInstanceSize(extra));
    
        //Gcc的内建函数 __builtin_constant_p 用于判断一个值是否为编译时常数,如果参数EXP 的值是常数,函数返回 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个字节
            return align16(size + extra - FAST_CACHE_ALLOC_DELTA16);
        }
    }
    

    3、align16的这个方法是16字节对齐算法

    //16字节对齐算法
    static inline size_t align16(size_t x) {
        return (x + size_t(15)) & ~size_t(15);
    }
    

    init 源码探索

    init的源码实现有以下两种

    1、类方法 init
    + (id)init {
        return (id)self;
    }
    
    2、实例方法 init
    - (id)init {
        return _objc_rootInit(self);
    }
    

    _objc_rootInit的源码实现

    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];
    }
    

    通过源码可以得知,new函数中直接调用了callAlloc函数(即alloc中分析的函数),且调用了init函数,所以可以得出new 其实就等价于 [alloc init]的结论

    但是一般开发中并不建议使用new,主要是因为有时会重写init方法做一些自定义的操作,用new初始化可能会无法走到自定义的部分。


    总结:

    1、 通过对alloc源码的分析,可以得知alloc的主要目的就是开辟内存,而且开辟的内存需要使用16字节对齐算法,现在开辟的内存的大小基本上都是16的整数倍
    开辟内存的核心步骤有3步:计算 -- 申请 -- 关联
    2、对init的源码分析,可得知 直接返回了obj,里面什么也没有做,而我们自定义一个对象,定义他的属性,在它初始化的时候,它就有一些默认值,比如,占位图、占位字符,我们需要重写init方法,在它的初始化方法中,给这些属性赋值,这就是init的作用。
    3 、而 new 则是对 allocinit 的简写形式而已,但是一般开发中并不建议使用new,主要是因为有时会重写init方法做一些自定义的操作,用new初始化可能会无法走到自定义的部分。

    相关文章

      网友评论

          本文标题:不用但一定要懂 ---- iOS 之 alloc&init 原理

          本文链接:https://www.haomeiwen.com/subject/aeqxmrtx.html