今天来根据objc4源码来探究下alloc流程,并从源码角度理解字节对齐、对象内存大小等概念;
总流程预览图
详细源码分析
第一步
从程序主入口执行创建NSObject对象
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
NSLog(@"Hello, World!");
NSObject *objc = [NSObject alloc];
}
return 0;
}
根据代码层层跳转
+ (id)alloc {
return _objc_rootAlloc(self);
}
==>
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;
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));
}
==>
id
_objc_rootAllocWithZone(Class cls, malloc_zone_t *zone __unused)
{
// allocWithZone under __OBJC2__ ignores the zone parameter
return _class_createInstanceFromZone(cls, 0, nil,
OBJECT_CONSTRUCT_CALL_BADALLOC);
}
第一个分析重点:callAlloc方法里的代码内容
首先此处有个宏定义判断
#if __OBJC2__
OBJC2 表示objective-c 2.0以上版本,
所以此处会执行OBJC2内的代码
if (slowpath(checkNil && !cls)) return nil;
进行判空操作,如果class不存在返回nil;
if (fastpath(!cls->ISA()->hasCustomAWZ())) {
return _objc_rootAllocWithZone(cls, nil);
}
如果!cls->ISA()->hasCustomAWZ() 则执行_objc_rootAllocWithZone
备注:关于slowpath和fastpath可自行百度其详细作用,主要是告诉编译器哪种路径的可能性更大,方便编译器编译时把更可能执行的代码安排在更接近起始处,减少了代码的分支执行,优化执行速度
// 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));
根据前一句代码 return callAlloc(cls, false, true);
allocWithZone = true
若fastpath为否,则会执行
return ((id(*)(id, SEL, struct _NSZone *))objc_msgSend)(cls,@selector(allocWithZone:), nil);
第二步
这一步也是alloc的核心方法
/*方法的参数:_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());
// 读取类的信息来决定后续的操作
bool hasCxxCtor = cxxConstruct && cls->hasCxxCtor();
bool hasCxxDtor = cls->hasCxxDtor();
bool fast = cls->canAllocNonpointer();
size_t size;
//计算类的内存大小,进行内存对齐
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) {
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);
}
这个方法比较复杂,但我们只需要关注核心的步骤
1、计算要分配的内存大小,为8的整数倍,少于16补足16
inline 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;
}
// 字节对齐 (NSObject 的结构体只有Class *isa 这一个成员变量,所以unalignedInstanceSize() = 8 )
uint32_t alignedInstanceSize() const {
return word_align(unalignedInstanceSize());
}
//字节对齐算法 WORD_MASK = 7 (如果16位对齐就是WORD_MASK = 15)
static inline uint32_t word_align(uint32_t x) {
return (x + WORD_MASK) & ~WORD_MASK;
}
经过这一系列步骤后便可获得size = 16/24/32,
问题1:为什么要进行少于16位补足16?
为了给内存计算留下容错空间。
问题2:为什么要进行字节对齐呢?
为了方便内存计算,如果对象的内存都大小不一,从CPU计算的角度看,这会消耗大量的cpu计算的时间。
问题3:为什么是8位的倍数,不是16或者更小呢?
iOS的64位架构cpu的指针大小为8个字节,所以一般我们使用的基础变量类型最大的内存大小为8位,这已经满足变量储存的需要了,故8个字节是最巧当的
2、根据内存大小分配内存
if (zone) {
obj = (id)malloc_zone_calloc((malloc_zone_t *)zone, 1, size);
} else {
obj = (id)calloc(1, size);
}
3、将内存地址绑定到类
if (!zone && fast) {
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);
}
最后 return obj;
MARK:后续再分析下内存地址绑定到类的过程