- 1. alloc流程
- 1.4.3 isa 类型
- if ARM_ARCH_7K >= 2 || (arm64 && !LP64)
- define SUPPORT_INDEXED_ISA 1
- else
- define SUPPORT_INDEXED_ISA 0
- endif
- if (!LP64 || TARGET_OS_WIN32 || \
- define SUPPORT_PACKED_ISA 0
- else
- define SUPPORT_PACKED_ISA 1
- endif
- if !SUPPORT_INDEXED_ISA && !SUPPORT_PACKED_ISA
- define SUPPORT_NONPOINTER_ISA 0
- else
- define SUPPORT_NONPOINTER_ISA 1
- endif
- 3. new
Person *objc2 = [Person alloc];Person *objc3 = [objc2 init];Person *objc4 = [objc2 init];Person *objc5 = [Person new];NSLog(@"%@ --- %p----%p",objc2, objc2, &objc2);NSLog(@"%@ --- %p----%p",objc3, objc3, &objc3);NSLog(@"%@ --- %p----%p",objc4, objc4, &objc4);NSLog(@"%@ --- %p----%p",objc5, objc5, &objc5);// 打印结果// <Person: 0x101354790> --- 0x101354790----0x7ffeefbff550// <Person: 0x101354790> --- 0x101354790----0x7ffeefbff538// <Person: 0x101354790> --- 0x101354790----0x7ffeefbff540// <Person: 0x101353110> --- 0x101353110----0x7ffeefbff548
在日常开发中,alloc, init, new 是最为常用的。今天来看看调用方法的时候,底层都做了什么~
objc4源码下载地址:obj4源码地址
1. alloc流程
1.1 代码段1 - callAlloc
+ (id)alloc {return _objc_rootAlloc(self);}id_objc_rootAlloc(Class cls){return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);}static ALWAYS_INLINE idcallAlloc(Class cls, bool checkNil, bool allocWithZone=false){// 新版 objc2中,isa的类型为isa_t#if __OBJC2__if (slowpath(checkNil && !cls)) return nil;// 当前类或者父类是否有自定义的 allocWithZone 方法实现if (fastpath(!cls->ISA()->hasCustomAWZ())) {return _objc_rootAllocWithZone(cls, nil);}#endif// 旧版 objc中,isa的类型为isa_t 为 Classif (allocWithZone) {return ((id(*)(id, SEL, struct _NSZone *))objc_msgSend)(cls, @selector(allocWithZone:), nil);}return ((id(*)(id, SEL))objc_msgSend)(cls, @selector(alloc));}
1.1.1 ALWAYS_INLINE
ALWAYS_INLINE 宏会强制开启 inline,inline 是一种降低函数调用成本的方法, 本质是在调用声明为 inline 的函数时,会直接把函数的实现替换过去,以空间换时间,当然滥用 inline 也会导致应用程序的体积增大。
#define ALWAYS_INLINE inline __attribute__((always_inline))
1.1.2 重点1:编译器优化
1. objc 源码中的编译器优化
slowpath 与 fastpath 的定义:
// bool(x)为 1 的概率大#define fastpath(x) (__builtin_expect(bool(x), 1))// bool(x)为 0 的概率大#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是创建对象的核心方法,主要包含以下三步:
- 计算所需内存大小
- 开辟内存空间,并返回地址
关联对象和类
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// 是否有构造方法的实现,constructbool hasCxxCtor = cxxConstruct && cls->hasCxxCtor();// 是否有析构方法的实现,destructbool hasCxxDtor = cls->hasCxxDtor();// isa 的类型是否为 isa_t ,objc 2.0中 isa 的类型都是使用 isa_t 的,旧版使用Classbool fast = cls->canAllocNonpointer();size_t size;// 1. 计算所需内存大小size = cls->instanceSize(extraBytes);if (outAllocatedSize) *outAllocatedSize = size;// 2. 开辟内存空间,并返回地址id obj;if (zone) {// 不会走,已经废弃了zone开辟空间obj = (id)malloc_zone_calloc((malloc_zone_t *)zone, 1, size);} else {// calloc()会默认的把申请出来的空间初始化为 0 或者 nilobj = (id)calloc(1, size);}if (slowpath(!obj)) {if (construct_flags & OBJECT_CONSTRUCT_CALL_BADALLOC) {return _objc_callBadAllocHandler(cls);}return nil;}// 3. 关联对象与类if (!zone && fast) {// nonpointer 的情况下关联 isaobj->initInstanceIsa(cls, hasCxxDtor);} else {// Use raw pointer isa on the assumption that they might be// doing something weird with the zone or RR.// 非nonpointer 的情况下关联 isaobj->initIsa(cls);}if (fastpath(!hasCxxCtor)) {return obj;}construct_flags |= OBJECT_CONSTRUCT_FREE_ONFAILURE;return object_cxxConstructFromClass(obj, cls, construct_flags);}
1.3 代码段3 - instanceSize
instanceSize -计算内存大小流程:
- 有缓存时,在缓存中取,并 16 字节对齐
- 无缓存时,64 位的设备是 8 字节对齐,32 位的是 4 字节对齐。
CF中要求所有的对象至少 16 字节(早期是 8 字节)。是因为第一个成员
isa占用 8 字节,如果多个对象在只有isa成员时,所有对象的isa地址紧挨着,可能会出现访问混乱的问题。为使访问更加安全,当没有别的属性时,会预留8字节,至少每个对象占 16 字节内存空间。size_t instanceSize(size_t extraBytes) const {// 有缓存的可能性大if (fastpath(cache.hasFastInstanceSize(extraBytes))) {return cache.fastInstanceSize(extraBytes);}size_t size = alignedInstanceSize() + extraBytes;// CF requires all objects be at least 16 bytes.if (size < 16) size = 16;return size;}
1.3.1 代码段3.1 - fastInstanceSize
```c size_t fastInstanceSize(size_t extra) const { ASSERT(hasFastInstanceSize(extra));
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 setFastInstanceSizereturn align16(size + extra - FAST_CACHE_ALLOC_DELTA16);
} }
static inline size_t align16(size_t x) { return (x + size_t(15)) & ~size_t(15); }
<a name="2BRyR"></a>### 1.3.2 代码段3.2 - **alignedInstanceSize**```c// Class's ivar size rounded up to a pointer-size boundary.uint32_t alignedInstanceSize() const {return word_align(unalignedInstanceSize());}static inline size_t word_align(size_t x) {return (x + WORD_MASK) & ~WORD_MASK;}#ifdef __LP64__# define WORD_SHIFT 3UL# define WORD_MASK 7UL# define WORD_BITS 64#else# define WORD_SHIFT 2UL# define WORD_MASK 3UL# define WORD_BITS 32#endif
1.3.3 重点2 - 字节对齐
1. 为什么字节对齐
通常内存是由一个个字节组成的。CPU 存取数据时,数据不是以字节为单位存储,而是以块为单位存储。频繁存取字节未对其的数据,会降低CPU的性能。所以数据块需要字节对齐。
更多字节对齐内容,移步☞ 字节对齐
1.4 代码段4 - initIsa
// nonpointer 的情况下关联 isainline voidobjc_object::initInstanceIsa(Class cls, bool hasCxxDtor){ASSERT(!cls->instancesRequireRawIsa());ASSERT(hasCxxDtor == cls->hasCxxDtor());initIsa(cls, true, hasCxxDtor);}// 非 nonpointer 的情况下关联 isainline voidobjc_object::initIsa(Class cls, bool nonpointer, bool hasCxxDtor){ASSERT(!isTaggedPointer());if (!nonpointer) {isa = isa_t((uintptr_t)cls);} else {ASSERT(!DisableNonpointerIsa);ASSERT(!cls->instancesRequireRawIsa());isa_t newisa(0);#if SUPPORT_INDEXED_ISAASSERT(cls->classArrayIndex() > 0);newisa.bits = ISA_INDEX_MAGIC_VALUE;// isa.magic is part of ISA_MAGIC_VALUE// isa.nonpointer is part of ISA_MAGIC_VALUEnewisa.has_cxx_dtor = hasCxxDtor;newisa.indexcls = (uintptr_t)cls->classArrayIndex();#elsenewisa.bits = ISA_MAGIC_VALUE;// isa.magic is part of ISA_MAGIC_VALUE// isa.nonpointer is part of ISA_MAGIC_VALUEnewisa.has_cxx_dtor = hasCxxDtor;newisa.shiftcls = (uintptr_t)cls >> 3;#endif// This write must be performed in a single store in some cases// (for example when realizing a class because other threads// may simultaneously try to use the class).// fixme use atomics here to guarantee single-store and to// guarantee memory order w.r.t. the class index table// ...but not too atomic because we don't want to hurt instantiationisa = newisa;}}
1.4.1 isa_t 的定义
union(联合体): 其中成员变量共用同一块地址空间,也就是说同一个内存段可以用来存放几种不同类型的成员,需要注意的是在每一瞬间只能存放其中的一种,而不是同时存放几种。
union isa_t{isa_t() { }isa_t(uintptr_t value) : bits(value) { }Class cls;uintptr_t bits;#if defined(ISA_BITFIELD)struct {ISA_BITFIELD; // defined in isa.h};#endif};
1.4.2 ISA_BITFIELD 的定义
#if SUPPORT_PACKED_ISA# if __arm64__// 掩码# define ISA_MASK 0x0000000ffffffff8ULL# define ISA_MAGIC_MASK 0x000003f000000001ULL// 魔数# define ISA_MAGIC_VALUE 0x000001a000000001ULL# define ISA_BITFIELD \uintptr_t nonpointer : 1; \uintptr_t has_assoc : 1; \uintptr_t has_cxx_dtor : 1; \uintptr_t shiftcls : 33; /*MACH_VM_MAX_ADDRESS 0x1000000000*/ \uintptr_t magic : 6; \uintptr_t weakly_referenced : 1; \uintptr_t deallocating : 1; \uintptr_t has_sidetable_rc : 1; \uintptr_t extra_rc : 19# define RC_ONE (1ULL<<45)# define RC_HALF (1ULL<<18)# elif __x86_64__# define ISA_MASK 0x00007ffffffffff8ULL# define ISA_MAGIC_MASK 0x001f800000000001ULL# define ISA_MAGIC_VALUE 0x001d800000000001ULL# define ISA_BITFIELD \uintptr_t nonpointer : 1; \uintptr_t has_assoc : 1; \uintptr_t has_cxx_dtor : 1; \uintptr_t shiftcls : 44; /*MACH_VM_MAX_ADDRESS 0x7fffffe00000*/ \uintptr_t magic : 6; \uintptr_t weakly_referenced : 1; \uintptr_t deallocating : 1; \uintptr_t has_sidetable_rc : 1; \uintptr_t extra_rc : 8# define RC_ONE (1ULL<<56)# define RC_HALF (1ULL<<7)# else# error unknown architecture for packed isa# endif#endif
结构体参数
nonpointer: 代表是否开启 NONPOINTER isa 指针优化,之前的版本又叫 index 的其实一个意思苹果后来给这类优化方案起了名字 NONPOINTERhas_assoc: 对象是否含有关联引用has_cxx_dtor: 对象是否含有 C++ 或者 Objc 的析构器shiftcls: 类的指针 arm64 下 33 bits,x86_64 下 44bitsmagic: 判断对象是否初始化完成 arm 下 0x16 ,x86_64下 0x3bweakly_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 || \
(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
- **SUPPORT_INDEXED_ISA = 1, isa 字段存储的是 class 在 class table 中的索引**- **SUPPORT_PACKED_ISA = 1,isa 字段存储的是以 mask 方式存储的 class指针**- **SUPPORT_NONPOINTER_ISA = 1,表示支持优化的 isa 指针,isa 的内容不再是类的指针了,而是包含了更多信息,比如引用计数,析构状态,被其他 weak 变量引用情况。**<a name="v288H"></a># 2. init**init只是返回了本对象,什么都没做**```c+ (id)init {return (id)self;}- (id)init {return _objc_rootInit(self);}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;}
3. new
new是直接调用了alloc init,是一种快捷创建对象的方式。如果想自定义初始化方法,不能使用new方法
+ (id)new {return [callAlloc(self, false/*checkNil*/) init];}
