1. Person *objc2 = [Person alloc];
  2. Person *objc3 = [objc2 init];
  3. Person *objc4 = [objc2 init];
  4. Person *objc5 = [Person new];
  5. NSLog(@"%@ --- %p----%p",objc2, objc2, &objc2);
  6. NSLog(@"%@ --- %p----%p",objc3, objc3, &objc3);
  7. NSLog(@"%@ --- %p----%p",objc4, objc4, &objc4);
  8. NSLog(@"%@ --- %p----%p",objc5, objc5, &objc5);
  9. // 打印结果
  10. // <Person: 0x101354790> --- 0x101354790----0x7ffeefbff550
  11. // <Person: 0x101354790> --- 0x101354790----0x7ffeefbff538
  12. // <Person: 0x101354790> --- 0x101354790----0x7ffeefbff540
  13. // <Person: 0x101353110> --- 0x101353110----0x7ffeefbff548

在日常开发中,alloc, init, new 是最为常用的。今天来看看调用方法的时候,底层都做了什么~
objc4源码下载地址:obj4源码地址

1. alloc流程

alloc.png

1.1 代码段1 - callAlloc

  1. + (id)alloc {
  2. return _objc_rootAlloc(self);
  3. }
  4. id
  5. _objc_rootAlloc(Class cls)
  6. {
  7. return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
  8. }
  9. static ALWAYS_INLINE id
  10. callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
  11. {
  12. // 新版 objc2中,isa的类型为isa_t
  13. #if __OBJC2__
  14. if (slowpath(checkNil && !cls)) return nil;
  15. // 当前类或者父类是否有自定义的 allocWithZone 方法实现
  16. if (fastpath(!cls->ISA()->hasCustomAWZ())) {
  17. return _objc_rootAllocWithZone(cls, nil);
  18. }
  19. #endif
  20. // 旧版 objc中,isa的类型为isa_t 为 Class
  21. if (allocWithZone) {
  22. return ((id(*)(id, SEL, struct _NSZone *))objc_msgSend)(cls, @selector(allocWithZone:), nil);
  23. }
  24. return ((id(*)(id, SEL))objc_msgSend)(cls, @selector(alloc));
  25. }

1.1.1 ALWAYS_INLINE

ALWAYS_INLINE 宏会强制开启 inline,inline 是一种降低函数调用成本的方法, 本质是在调用声明为 inline 的函数时,会直接把函数的实现替换过去,以空间换时间,当然滥用 inline 也会导致应用程序的体积增大。

  1. #define ALWAYS_INLINE inline __attribute__((always_inline))

1.1.2 重点1:编译器优化

1. objc 源码中的编译器优化

slowpath 与 fastpath 的定义:

  1. // bool(x)为 1 的概率大
  2. #define fastpath(x) (__builtin_expect(bool(x), 1))
  3. // bool(x)为 0 的概率大
  4. #define slowpath(x) (__builtin_expect(bool(x), 0))

__builtin_expect(exp, N) 是 GCC 提供给程序员的。表示exp为N的可能性更大。允许程序员将最有可能执行的代码分支告诉编译器。编译器将执行可能性更大的代码紧跟着前面的代码,用于优化代码执行效率,提高预读指令的命中率,以减少指令跳转带来的性能下降。

2. xcode设置编译器优化级别

可以通过修改 Build Settings > Optimization Level 来更改编译器优化级别,指定被编译代码的执行速度和二进制文件大小的优化程度:

  • None[-O0]: 不优化。在这种设置下, 编译器的目标是降低编译消耗,保证调试时输出期望的结果。程序的语句之间是独立的:如果在程序的停在某一行的断点出,我们可以给任何变量赋新值抑或是将程序计数器指向方法中的任何一个语句,并且能得到一个和源码完全一致的运行结果。
  • Fast[-O1]: 大函数所需的编译时间和内存消耗都会稍微增加。在这种设置下,编译器会尝试减小代码文件的大小,减少执行时间,但并不执行需要大量编译时间的优化。在苹果的编译器中,在优化过程中,严格别名,块重排和块间的调度都会被默认禁止掉。
  • Faster[-O2]: 编译器执行所有不涉及时间空间交换的所有的支持的优化选项。在这种设置下,编译器不会进行循环展开、函数内联或寄存器重命名。和‘Fast[-O1]’项相比,此设置会增加编译时间和生成代码的性能。
  • Fastest[-O3]: 在开启‘Fast[-O1]’项支持的所有优化项的同时,开启函数内联和寄存器重命名选项。这个设置有可能会导致二进制文件变大。
  • Fastest, Smallest[-Os]: 优化大小。这个设置开启了‘Fast[-O1]’项中的所有不增加代码大小的优化选项,并会进一步的执行可以减小代码大小的优化。
  • Fastest, Aggressive Optimizations[-Ofast]: 这个设置开启了“Fastest[-O3]”中的所有优化选项,同时也开启了可能会打破严格编译标准的积极优化,但并不会影响运行良好的代码。

在Xcode中,为了方便调试,通常Debug模式默认为None[-O0],Release模式默认为Fastest, Smallest[-Os],在实际的项目中,可以根据项目的情况设置优化级别。

1.2 代码段2 - _class_createInstanceFromZone

_class_createInstanceFromZone是创建对象的核心方法,主要包含以下三步:

  1. 计算所需内存大小
  2. 开辟内存空间,并返回地址
  3. 关联对象和类

    1. static ALWAYS_INLINE id
    2. _class_createInstanceFromZone(Class cls, size_t extraBytes, void *zone,
    3. int construct_flags = OBJECT_CONSTRUCT_NONE,
    4. bool cxxConstruct = true,
    5. size_t *outAllocatedSize = nil)
    6. {
    7. ASSERT(cls->isRealized());
    8. // Read class's info bits all at once for performance
    9. // 是否有构造方法的实现,construct
    10. bool hasCxxCtor = cxxConstruct && cls->hasCxxCtor();
    11. // 是否有析构方法的实现,destruct
    12. bool hasCxxDtor = cls->hasCxxDtor();
    13. // isa 的类型是否为 isa_t ,objc 2.0中 isa 的类型都是使用 isa_t 的,旧版使用Class
    14. bool fast = cls->canAllocNonpointer();
    15. size_t size;
    16. // 1. 计算所需内存大小
    17. size = cls->instanceSize(extraBytes);
    18. if (outAllocatedSize) *outAllocatedSize = size;
    19. // 2. 开辟内存空间,并返回地址
    20. id obj;
    21. if (zone) {
    22. // 不会走,已经废弃了zone开辟空间
    23. obj = (id)malloc_zone_calloc((malloc_zone_t *)zone, 1, size);
    24. } else {
    25. // calloc()会默认的把申请出来的空间初始化为 0 或者 nil
    26. obj = (id)calloc(1, size);
    27. }
    28. if (slowpath(!obj)) {
    29. if (construct_flags & OBJECT_CONSTRUCT_CALL_BADALLOC) {
    30. return _objc_callBadAllocHandler(cls);
    31. }
    32. return nil;
    33. }
    34. // 3. 关联对象与类
    35. if (!zone && fast) {
    36. // nonpointer 的情况下关联 isa
    37. obj->initInstanceIsa(cls, hasCxxDtor);
    38. } else {
    39. // Use raw pointer isa on the assumption that they might be
    40. // doing something weird with the zone or RR.
    41. // 非nonpointer 的情况下关联 isa
    42. obj->initIsa(cls);
    43. }
    44. if (fastpath(!hasCxxCtor)) {
    45. return obj;
    46. }
    47. construct_flags |= OBJECT_CONSTRUCT_FREE_ONFAILURE;
    48. return object_cxxConstructFromClass(obj, cls, construct_flags);
    49. }

    1.3 代码段3 - instanceSize

    instanceSize -计算内存大小流程:

  • 有缓存时,在缓存中取,并 16 字节对齐
  • 无缓存时,64 位的设备是 8 字节对齐,32 位的是 4 字节对齐。
  • CF中要求所有的对象至少 16 字节(早期是 8 字节)。是因为第一个成员 isa 占用 8 字节,如果多个对象在只有 isa 成员时,所有对象的 isa 地址紧挨着,可能会出现访问混乱的问题。为使访问更加安全,当没有别的属性时,会预留8字节,至少每个对象占 16 字节内存空间。

    1. size_t instanceSize(size_t extraBytes) const {
    2. // 有缓存的可能性大
    3. if (fastpath(cache.hasFastInstanceSize(extraBytes))) {
    4. return cache.fastInstanceSize(extraBytes);
    5. }
    6. size_t size = alignedInstanceSize() + extraBytes;
    7. // CF requires all objects be at least 16 bytes.
    8. if (size < 16) size = 16;
    9. return size;
    10. }

    1.3.1 代码段3.1 - fastInstanceSize

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

    if (__builtin_constant_p(extra) && extra == 0) {

    1. return _flags & FAST_CACHE_ALLOC_MASK16;

    } else {

    1. size_t size = _flags & FAST_CACHE_ALLOC_MASK;
    2. // remove the FAST_CACHE_ALLOC_DELTA16 that was added
    3. // by setFastInstanceSize
    4. return align16(size + extra - FAST_CACHE_ALLOC_DELTA16);

    } }

static inline size_t align16(size_t x) { return (x + size_t(15)) & ~size_t(15); }

  1. <a name="2BRyR"></a>
  2. ### 1.3.2 代码段3.2 - **alignedInstanceSize**
  3. ```c
  4. // Class's ivar size rounded up to a pointer-size boundary.
  5. uint32_t alignedInstanceSize() const {
  6. return word_align(unalignedInstanceSize());
  7. }
  8. static inline size_t word_align(size_t x) {
  9. return (x + WORD_MASK) & ~WORD_MASK;
  10. }
  11. #ifdef __LP64__
  12. # define WORD_SHIFT 3UL
  13. # define WORD_MASK 7UL
  14. # define WORD_BITS 64
  15. #else
  16. # define WORD_SHIFT 2UL
  17. # define WORD_MASK 3UL
  18. # define WORD_BITS 32
  19. #endif

1.3.3 重点2 - 字节对齐

1. 为什么字节对齐

通常内存是由一个个字节组成的。CPU 存取数据时,数据不是以字节为单位存储,而是以块为单位存储。频繁存取字节未对其的数据,会降低CPU的性能。所以数据块需要字节对齐。
更多字节对齐内容,移步☞ 字节对齐

1.4 代码段4 - initIsa

  1. // nonpointer 的情况下关联 isa
  2. inline void
  3. objc_object::initInstanceIsa(Class cls, bool hasCxxDtor)
  4. {
  5. ASSERT(!cls->instancesRequireRawIsa());
  6. ASSERT(hasCxxDtor == cls->hasCxxDtor());
  7. initIsa(cls, true, hasCxxDtor);
  8. }
  9. // 非 nonpointer 的情况下关联 isa
  10. inline void
  11. objc_object::initIsa(Class cls, bool nonpointer, bool hasCxxDtor)
  12. {
  13. ASSERT(!isTaggedPointer());
  14. if (!nonpointer) {
  15. isa = isa_t((uintptr_t)cls);
  16. } else {
  17. ASSERT(!DisableNonpointerIsa);
  18. ASSERT(!cls->instancesRequireRawIsa());
  19. isa_t newisa(0);
  20. #if SUPPORT_INDEXED_ISA
  21. ASSERT(cls->classArrayIndex() > 0);
  22. newisa.bits = ISA_INDEX_MAGIC_VALUE;
  23. // isa.magic is part of ISA_MAGIC_VALUE
  24. // isa.nonpointer is part of ISA_MAGIC_VALUE
  25. newisa.has_cxx_dtor = hasCxxDtor;
  26. newisa.indexcls = (uintptr_t)cls->classArrayIndex();
  27. #else
  28. newisa.bits = ISA_MAGIC_VALUE;
  29. // isa.magic is part of ISA_MAGIC_VALUE
  30. // isa.nonpointer is part of ISA_MAGIC_VALUE
  31. newisa.has_cxx_dtor = hasCxxDtor;
  32. newisa.shiftcls = (uintptr_t)cls >> 3;
  33. #endif
  34. // This write must be performed in a single store in some cases
  35. // (for example when realizing a class because other threads
  36. // may simultaneously try to use the class).
  37. // fixme use atomics here to guarantee single-store and to
  38. // guarantee memory order w.r.t. the class index table
  39. // ...but not too atomic because we don't want to hurt instantiation
  40. isa = newisa;
  41. }
  42. }

1.4.1 isa_t 的定义

union(联合体): 其中成员变量共用同一块地址空间,也就是说同一个内存段可以用来存放几种不同类型的成员,需要注意的是在每一瞬间只能存放其中的一种,而不是同时存放几种。

  1. union isa_t
  2. {
  3. isa_t() { }
  4. isa_t(uintptr_t value) : bits(value) { }
  5. Class cls;
  6. uintptr_t bits;
  7. #if defined(ISA_BITFIELD)
  8. struct {
  9. ISA_BITFIELD; // defined in isa.h
  10. };
  11. #endif
  12. };

1.4.2 ISA_BITFIELD 的定义

  1. #if SUPPORT_PACKED_ISA
  2. # if __arm64__
  3. // 掩码
  4. # define ISA_MASK 0x0000000ffffffff8ULL
  5. # define ISA_MAGIC_MASK 0x000003f000000001ULL
  6. // 魔数
  7. # define ISA_MAGIC_VALUE 0x000001a000000001ULL
  8. # define ISA_BITFIELD \
  9. uintptr_t nonpointer : 1; \
  10. uintptr_t has_assoc : 1; \
  11. uintptr_t has_cxx_dtor : 1; \
  12. uintptr_t shiftcls : 33; /*MACH_VM_MAX_ADDRESS 0x1000000000*/ \
  13. uintptr_t magic : 6; \
  14. uintptr_t weakly_referenced : 1; \
  15. uintptr_t deallocating : 1; \
  16. uintptr_t has_sidetable_rc : 1; \
  17. uintptr_t extra_rc : 19
  18. # define RC_ONE (1ULL<<45)
  19. # define RC_HALF (1ULL<<18)
  20. # elif __x86_64__
  21. # define ISA_MASK 0x00007ffffffffff8ULL
  22. # define ISA_MAGIC_MASK 0x001f800000000001ULL
  23. # define ISA_MAGIC_VALUE 0x001d800000000001ULL
  24. # define ISA_BITFIELD \
  25. uintptr_t nonpointer : 1; \
  26. uintptr_t has_assoc : 1; \
  27. uintptr_t has_cxx_dtor : 1; \
  28. uintptr_t shiftcls : 44; /*MACH_VM_MAX_ADDRESS 0x7fffffe00000*/ \
  29. uintptr_t magic : 6; \
  30. uintptr_t weakly_referenced : 1; \
  31. uintptr_t deallocating : 1; \
  32. uintptr_t has_sidetable_rc : 1; \
  33. uintptr_t extra_rc : 8
  34. # define RC_ONE (1ULL<<56)
  35. # define RC_HALF (1ULL<<7)
  36. # else
  37. # error unknown architecture for packed isa
  38. # endif
  39. #endif

结构体参数
  • nonpointer : 代表是否开启 NONPOINTER isa 指针优化,之前的版本又叫 index 的其实一个意思苹果后来给这类优化方案起了名字 NONPOINTER
  • has_assoc: 对象是否含有关联引用
  • has_cxx_dtor: 对象是否含有 C++ 或者 Objc 的析构器
  • shiftcls: 类的指针 arm64 下 33 bits,x86_64 下 44bits
  • magic: 判断对象是否初始化完成 arm 下 0x16 ,x86_64下 0x3b
  • weakly_referenced: 是否为弱引用的对象
  • deallocating:对象是否正在执行析构函数(是否在释放内存)
  • has_sidetable_rc:判断是否需要用 sidetable 去处理引用计数,( extra_rc 的大小影响到这个变量)
  • extra_rc:存储该对象的引用计数值减一后的结果

    1.4.3 isa 类型

    ```c // Define SUPPORT_INDEXED_ISA=1 on platforms that store the class in the isa // field as an index into a class table. // Note, keep this in sync with any .s files which also define it. // Be sure to edit objc-abi.h as well.

    if ARM_ARCH_7K >= 2 || (arm64 && !LP64)

    define SUPPORT_INDEXED_ISA 1

    else

    define SUPPORT_INDEXED_ISA 0

    endif

// Define SUPPORT_PACKED_ISA=1 on platforms that store the class in the isa // field as a maskable pointer with other data around it.

if (!LP64 || TARGET_OS_WIN32 || \

  1. (TARGET_OS_SIMULATOR && !TARGET_OS_IOSMAC))

define SUPPORT_PACKED_ISA 0

else

define SUPPORT_PACKED_ISA 1

endif

// Define SUPPORT_NONPOINTER_ISA=1 on any platform that may store something // in the isa field that is not a raw pointer.

if !SUPPORT_INDEXED_ISA && !SUPPORT_PACKED_ISA

define SUPPORT_NONPOINTER_ISA 0

else

define SUPPORT_NONPOINTER_ISA 1

endif

  1. - **SUPPORT_INDEXED_ISA = 1, isa 字段存储的是 class 在 class table 中的索引**
  2. - **SUPPORT_PACKED_ISA = 1,isa 字段存储的是以 mask 方式存储的 class指针**
  3. - **SUPPORT_NONPOINTER_ISA = 1,表示支持优化的 isa 指针,isa 的内容不再是类的指针了,而是包含了更多信息,比如引用计数,析构状态,被其他 weak 变量引用情况。**
  4. <a name="v288H"></a>
  5. # 2. init
  6. **init只是返回了本对象,什么都没做**
  7. ```c
  8. + (id)init {
  9. return (id)self;
  10. }
  11. - (id)init {
  12. return _objc_rootInit(self);
  13. }
  14. id
  15. _objc_rootInit(id obj)
  16. {
  17. // In practice, it will be hard to rely on this function.
  18. // Many classes do not properly chain -init calls.
  19. return obj;
  20. }

3. new

new是直接调用了alloc init,是一种快捷创建对象的方式。如果想自定义初始化方法,不能使用new方法

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