前言
在iOS日常開發(fā)中既鞠,我們經(jīng)常使用alloc init 方法來初始化對象般此,卻沒有去深究alloc在底層是如何執(zhí)行的,這篇文章將從底層源碼探索alloc的原理棘利。
首先,我們新建一個工程朽缴,并初始化一組對象善玫,打印他們的3個對象的內(nèi)容、內(nèi)存地址密强、指針地址茅郎。從上圖我們可以看出,3個對象指向的是同一個內(nèi)存空間或渤,所以其內(nèi)容和內(nèi)存地址是相同的系冗,但是對象的指針地址是不同的,為什么會這樣呢薪鹦,OC的底層是如何創(chuàng)建對象的呢掌敬?帶著問題惯豆,我們進入下一步的探索。
%p -> p1: 對象指針指向的的內(nèi)存地址
%p -> &p1:對象的指針地址
3種探索的方式
1.下符號斷點的形式奔害,跟著流程走
-
先打個斷點楷兽,代碼運行到斷點處,打個符號斷點
-
輸入alloc
-
點擊下一步
由上面流程可以看出objc_alloc是在libobjc.A.dylib動態(tài)庫創(chuàng)建的华临。
2.按住control+step into
-
在代碼運行至斷點處
-
接著打個符號斷點objc_alloc
由此發(fā)現(xiàn)objc_alloc在libobjc.A.dylib這個庫里面芯杀。
3.匯編查看
-運行代碼,在斷點處银舱,點擊Debug->Debug Workflow->Always Show Disassembly-
從匯編代碼callq處瘪匿,我們看到匯編調(diào)用了objc_alloc
-
下個符號斷點objc_alloc
從以上的探索我們得知,對象的alloc在libobjc.A.dylib中寻馏,于是我們從蘋果開發(fā)源中去下載源碼棋弥。
源碼下載
- 蘋果官方源碼下載地址
- 在這里給大家介紹一位大神已經(jīng)配置好的源碼GitHub,我們直接下載就可以使用了诚欠。
源碼探索
Person *objc1 = [Person alloc] ;
1.首先我們打開源碼顽染,創(chuàng)建一個對象,點擊進入alloc方法的源碼實現(xiàn)轰绵。
+ (id)alloc {
return _objc_rootAlloc(self);
}
2.點擊_objc_rootAlloc方法跳轉(zhuǎn)至_objc_rootAlloc
id
_objc_rootAlloc(Class cls)
{
return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}
3.點擊callAlloc方法跳轉(zhuǎn)至callAlloc的源碼實現(xiàn)粉寞。
static ALWAYS_INLINE id
callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
#if __OBJC2__ //有可用的編譯器優(yōu)化
if (slowpath(checkNil && !cls)) return nil;
if (fastpath(!cls->ISA()->hasCustomAWZ())) {
return _objc_rootAllocWithZone(cls, nil);
}
#endif
// No shortcuts available.
if (allocWithZone) { //沒有可用的編譯器優(yōu)化
return ((id(*)(id, SEL, struct _NSZone *))objc_msgSend)(cls, @selector(allocWithZone:), nil);
}
return ((id(*)(id, SEL))objc_msgSend)(cls, @selector(alloc));
}
通過打斷點,我們的代碼執(zhí)行了_objc_rootAllocWithZone方法左腔。
關(guān)于slowpath和fastpath唧垦,系統(tǒng)的定義如下:
#define fastpath(x) (__builtin_expect(bool(x), 1))
#define slowpath(x) (__builtin_expect(bool(x), 0))
- 首先我們要知道__builtin_expect是什么。其實液样,這個指令是gcc引入的振亮,作用是允許程序員將最有可能執(zhí)行的分支告訴編譯器。這個指令的寫法為:__builtin_expect(EXP, N)鞭莽。
- 目的:編譯器可以對代碼進行優(yōu)化坊秸,以減少指令跳轉(zhuǎn)帶來的性能下降,即性能優(yōu)化澎怒;
- 作用:允許程序員將最有可能執(zhí)行的分支告訴編譯器褒搔;
- 指令的寫法為:__builtin_expect(EXP, N)。表示 EXP==N的概率很大喷面;
- fastpath定義中__builtin_expect((x),1)表示 x 的值為真的可能性更大星瘾;即執(zhí)行 if 里面語句的機會更大;
- slowpath定義中的__builtin_expect((x),0)表示 x 的值為假的可能性更大乖酬,即執(zhí)行 else 里面語句的機會更大死相;
ls->ISA()->hasCustomAWZ(),這里用來判斷當(dāng)前class是否有自定義的allocWithZone咬像。顯然我們沒有自定義allocWithZone方法,所以!cls->ISA()->hasCustomAWZ())為true,代碼執(zhí)行_objc_rootAllocWithZone方法县昂。
4.跳轉(zhuǎn)至_objc_rootAllocWithZone源碼
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);
}
5.跳轉(zhuǎn)至_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
bool hasCxxCtor = cxxConstruct && cls->hasCxxCtor();
bool hasCxxDtor = cls->hasCxxDtor();
bool fast = cls->canAllocNonpointer();
size_t size;
// 1:要開辟多少內(nèi)存
size = cls->instanceSize(extraBytes);
if (outAllocatedSize) *outAllocatedSize = size;
id obj;
if (zone) {
obj = (id)malloc_zone_calloc((malloc_zone_t *)zone, 1, size);
} else {
// 2:怎么去申請內(nèi)存
obj = (id)calloc(1, size);
}
if (slowpath(!obj)) {
if (construct_flags & OBJECT_CONSTRUCT_CALL_BADALLOC) {
return _objc_callBadAllocHandler(cls);
}
return nil;
}
// 3:將當(dāng)前的類和指針地址綁定在一起
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);
}
alloc核心內(nèi)容
- 1.size = cls->instanceSize(extraBytes);計算要開辟的內(nèi)存大小肮柜。
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;
}
通過斷點調(diào)試,代碼執(zhí)行fastInstanceSize方法
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);
}
}
然后執(zhí)行align16方法待讳,這就是16字節(jié)對齊算法芒澜。
static inline size_t align16(size_t x) {
return (x + size_t(15)) & ~size_t(15);
}
- 通過calloc申請內(nèi)存,并賦值給obj创淡,因此 obj是指向內(nèi)存地址的指針
obj = (id)calloc(1, size);
- 3.通過initInstanceIsa痴晦,將當(dāng)前的類和指針地址綁定在一起
obj->initInstanceIsa(cls, hasCxxDtor);
以上就是alloc的探索過程,總結(jié)流程圖如下:總結(jié)
通過對alloc源碼的分析琳彩,可以得知alloc開辟內(nèi)存最小為16字節(jié)且為16的整數(shù)倍誊酌。
核心步驟:計算內(nèi)存空間大小->向系統(tǒng)申請->關(guān)聯(lián)到相應(yīng)的類。
init方法和new方法做了什么露乏?
- 查看源碼!
+ (id)init {
return (id)self;
}
init方法返回了強轉(zhuǎn)的self,這是構(gòu)造方法也是工廠設(shè)計碧浊,方便我們重寫init方法。
+ (id)new {
return [callAlloc(self, false/*checkNil*/) init];
}
new方法則返回[callAlloc init]