黑马程序员——Objective-C中3种枚举方法耗时比较——黑马 ios 技术博客

来源:互联网 发布:人工智能计算器v3.6.0 编辑:程序博客网 时间:2024/05/18 01:48

------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------

Objective-C中3种枚举方法耗时比较

MAR 11TH, 2014

集合类对象(NSArray、NSDictionary、NSSet及其子类)在Objective-C中十分常见。经常会有遍历集合中所有对象的需求,Objective-C中遍历集合中对象的方法有三种:

  1. C语言的for循环遍历;
  2. Objective-C的快速枚举;
  3. 集合对象的枚举块语法。

为了测试以上三种枚举方法消耗的时间,我写了一个小程序,对含有1万个元素的数组进行打印操作,看看分别都消耗了多长时间。核心代码如下:

Large Enumeration Test
123456789101112131415161718192021222324252627
NSUInteger totalCount = 10000;NSMutableArray *array = [NSMutableArray arrayWithCapacity:totalCount];        //create an array including 10000 elements    for (int i = 0; i<totalCount; i++) {        array[i] = [@(i) stringValue];    }        //C Language For Loop Enumeration    CFTimeInterval start1 = CACurrentMediaTime();    for (int j = 0; j< totalCount; j++) {        NSLog(@"%@",array[j]);    }    CFTimeInterval end1 = CACurrentMediaTime();    NSLog(@"C Language For Loop method %f",end1 - start1);        //Objective-C Fast Enumeration    CFTimeInterval start2 = CACurrentMediaTime();    for (NSString *string in array) {        NSLog(@"%@",string);    }    CFTimeInterval end2 = CACurrentMediaTime();    NSLog(@"Objective-C Fast Enumeration method %f",end2 - start2);        //Objective-C Block Enumeration    CFTimeInterval start3 = CACurrentMediaTime();    [array enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(NSString * obj, NSUInteger idx, BOOL *stop) {        NSLog(@"%@",obj);    }];    CFTimeInterval end3 = CACurrentMediaTime();    NSLog(@"Objective-C Block Enumeration method %f",end3 - start3);

其中CACurrentMediaTime()是一个返回系统时间的函数(苹果参考文档),可以通过结束时间减去开始时间计算代码所消耗的时间。(附:在Mac终端中输入w可以查询机器已经运行的时间信息,w属于Unix命令。)

部分运行结果:

Consume Time Results
123
2014-03-11 15:04:41.522 testspeed[19780:70b] C Language For Loop method 7.7507102014-03-11 15:04:47.847 testspeed[19780:70b] Objective-C Fast Enumeration method 6.3236732014-03-11 15:04:53.715 testspeed[19780:70b] Objective-C Block Enumeration method 5.866547

从以上结果可以看出,语法块的枚举耗时最短,快速枚举次之,for循环最慢。语法块枚举快的主要原因是枚举options中采用了NSEnumerationConcurrent,也就是并行处理,充分发挥了多核心的优势。当然这么做会导致输出顺序错乱,如果需求对顺序要求严格,就不能使用这个选项。


0 0
原创粉丝点击