打Log是我们debug时最简单朴素的方法,NSLog对于objc开发就像printf对于c一样重要。但在使用NSLog打印大量Log,尤其是在游戏开发时(如每一帧都打印数据),NSLog会明显的拖慢程序的运行速度(游戏帧速严重下滑)。本文探究了一下NSLog如此之慢的原因,并尝试使用lldb断点调试器替代NSLog进行debug log
测试下分别使用NSLog和printf打印10000次耗费的时间。CFAbsoluteTimeGetCurrent()函数可以打印出当前的时间戳,精度还是很高的,于是乎测试代码如下:
CFAbsoluteTimestartNSLog=CFAbsoluteTimeGetCurrent();
for(inti =0; i <10000; i++) {
NSLog(@"%d", i);
}
CFAbsoluteTimeendNSLog=CFAbsoluteTimeGetCurrent();
CFAbsoluteTimestartPrintf =CFAbsoluteTimeGetCurrent();
for(inti =0; i <10000; i++) {
printf("%d\n", i);
}
CFAbsoluteTimeendPrintf =CFAbsoluteTimeGetCurrent();
NSLog(@"NSLog time: %lf, printf time: %lf", endNSLog- startNSLog, endPrintf - startPrintf);
这个时间和机器肯定有关系,只看它们的差别就好。为了全面性,尝试了三种平台:
NSLogtime:4.985445, printf time:0.084193// mac
NSLogtime:5.562460, printf time:0.019408// 模拟器
NSLogtime:10.471490, printf time:0.090503// 真机调试(iphone5)
可以发现,在mac上(模拟器其实也算是mac吧)速度差别达到了60倍左右,而真机调试甚至达到了离谱的100多倍。
总结
NSLog耗费比较大的资源
NSLog被设计为error log,是ASL的高层封装
在项目中避免提交commit自己的Debug log,release版本更要注意去除NSLog,可以使用自建的log系统或好用的log系统来替代NSLog
debug不应只局限于log满天飞,lldb断点调试是一个优秀的debug方法,需要再深入研究下
网友评论