#define vs self.method用于检查分配

drU*_*lis 1 performance cocoa-touch objective-c ios c-preprocessor

我想知道检查对象的分配(或其他东西)的正确方法是什么.我自己做了一些性能测试,发现没有方法调用的检查可以节省"巨大"的时间.哪种方式被视为良好的编码?测试和结果如下.

定义:

#define checkUM if (!um) {um =  [[UtilityMaster alloc]init]; }
Run Code Online (Sandbox Code Playgroud)

与方法:

-(void) checkUtility {
    if (!um) {um =  [[UtilityMaster alloc]init]; }
}
Run Code Online (Sandbox Code Playgroud)

检查代码:

int imax = 1000000000;
int i = 0;
IFD100(@"check method")
while (i <= imax) {
    [self checkUtility];
    i++;
}
IFD100(@"check method end")
i = 0;
IFD100(@"check define")
while (i <= imax) {
    checkUM;
    i++;
}
IFD100(@"check define end")
Run Code Online (Sandbox Code Playgroud)

检查1:

2013-06-25 18:36:16.712  check method
2013-06-25 18:36:27.669  check method end  <-- 10.957 secs
2013-06-25 18:36:27.670  check define
2013-06-25 18:36:30.128  check define end  <-- 2.458 secs
Run Code Online (Sandbox Code Playgroud)

检查2:

2013-06-25 18:37:18.900  check method
2013-06-25 18:37:28.678  check method end  <-- 9.778 secs
2013-06-25 18:37:28.679  check define
2013-06-25 18:37:31.136  check define end  <-- 2.457 secs
Run Code Online (Sandbox Code Playgroud)

小智 5

预处理器宏很难看,尤其是当您尝试使用它们模拟函数时.所以不要这样做.与此同时,我怀疑这是你的算法的瓶颈.如果是,那么最好制作一个内联函数,让编译器完成它的优化工作.


mro*_*les 5

如果你打电话的话,可能值得考虑性能,但请记住,你称之为十亿次.这意味着每次呼叫需要大约9纳秒.那不是一个巨大的时间.另外,请记住#define是一个宏,意味着它实际上会将代码粘贴到您调用它的任何地方.按你的意思解释,这是你的选择,但我建议使用方法,因为它们更简单,更容易扩展等.如果有任何需要每次调用额外9纳秒的东西,它应该用直接c写.