1. 測試程序
main.mm
#import <Foundation/Foundation.h>
#import "OMTPerson.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
OMTPerson *p1 = [OMTPerson new];
OMTPerson *p2 = [[OMTPerson alloc] init];
NSLog(@"Hello world");
}
return 0;
}
代碼非常簡單,只是創(chuàng)建兩個對象
從這段代碼中可以看出使用了兩種不同的方式創(chuàng)建對象new
和 alloc init
诗力。
2. 從源碼中尋找答案
通過 cmd + 左鍵
跟進(jìn)代碼實(shí)現(xiàn)
// 類名: NSObject.mm
// 使用 new 創(chuàng)建的關(guān)鍵代碼
+ (id)new {
return [callAlloc(self, false/*checkNil*/) init];
}
// 使用 alloc 創(chuàng)建關(guān)鍵代碼
+ (id)alloc {
return _objc_rootAlloc(self);
}
id
_objc_rootAlloc(Class cls)
{
return callAlloc(cls, false/*checkNil*/, true/*allocWithZone*/);
}
// 內(nèi)聯(lián)函數(shù)真正實(shí)現(xiàn)對象創(chuàng)建
static ALWAYS_INLINE id
callAlloc(Class cls, bool checkNil, bool allocWithZone=false)
{
// 編譯器優(yōu)化,表示條件為假的可能性更大一些
if (slowpath(checkNil && !cls)) return nil;
// 此處認(rèn)為就是正官疲,一定會執(zhí)行
#if __OBJC2__
// 編譯器優(yōu)化搂漠,沒有實(shí)現(xiàn)自定義 allocWithZone 的可能性更大
if (fastpath(!cls->ISA()->hasCustomAWZ())) {
// No alloc/allocWithZone implementation. Go straight to the allocator.
// fixme store hasCustomAWZ in the non-meta class and
// add it to canAllocFast's summary
if (fastpath(cls->canAllocFast())) {
// No ctors, raw isa, etc. Go straight to the metal.
bool dtor = cls->hasCxxDtor();
id obj = (id)calloc(1, cls->bits.fastInstanceSize());
if (slowpath(!obj)) return callBadAllocHandler(cls);
obj->initInstanceIsa(cls, dtor);
return obj;
}
else {
// Has ctor or raw isa or something. Use the slower path.
// 本例中走的是這個分支
id obj = class_createInstance(cls, 0);
if (slowpath(!obj)) return callBadAllocHandler(cls);
return obj;
}
}
#endif
// No shortcuts available.
if (allocWithZone) return [cls allocWithZone:nil];
return [cls alloc];
}
后續(xù)流程都是一樣的迂卢。以下是兩種方法的簡單流程
// alloc
alloc->_objc_rootAlloc->callAlloc->class_createInstance(objc-runtime-new.mm)
->_class_createInstanceFromZone(objc-runtime-new.mm)
// new
new->callAlloc->class_createInstance(objc-runtime-new.mm)
->_class_createInstanceFromZone(objc-runtime-new.mm)
3. 結(jié)論
- 使用
new
方法創(chuàng)建實(shí)例時,少走一個_objc_rootAlloc
方法桐汤,理論上說要比alloc
更快一些 - 使用
new
方法創(chuàng)建實(shí)例時不需要自己手動調(diào)用init
方法