代码:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39#import <Foundation/Foundation.h> extern uint64_t dispatch_benchmark(size_t count, void (^block)(void)); void processNumber(NSNumber *n); int main(int argc, const char * argv[]) { @autoreleasepool { // 创建一个数组并用随机数填充 NSUInteger const capacity = 15; NSMutableArray *array = [NSMutableArray arrayWithCapacity:capacity]; for (NSUInteger i = 0; i < capacity; ++i) { [array addObject:@(arc4random_uniform(100))]; } size_t count = 10000000; // 使用for循环遍历数组 uint64_t time1 = dispatch_benchmark(count, ^{ for (NSUInteger i = 0; i < capacity; ++i) { processNumber(array[i]); } }); NSLog(@"for = %lluns", time1); // 使用forin循环遍历数组 uint64_t time2 = dispatch_benchmark(count, ^{ for (NSNumber *num in array) { processNumber(num); } }); NSLog(@"forin = %lluns", time2); // 使用block遍历数组 uint64_t time3 = dispatch_benchmark(count, ^{ [array enumerateObjectsUsingBlock:^(NSNumber *num, NSUInteger idx, BOOL *stop) { processNumber(num); }]; }); NSLog(@"block = %lluns", time3); } return 0; } void processNumber(NSNumber *n) { // code... }
输出:
复制代码
1
2
3for = 326ns forin = 237ns block = 638ns
但是如果把所有的processNumber函数注释掉,输出的结果如下:
复制代码
1
2
3for = 20ns forin = 106ns block = 496ns
所以对于遍历数组,不能武断的得出某种方式效率一定最高的结论,实际的执行效果往往取决于代码编写的情况。
转载于:https://www.cnblogs.com/xwoder/p/4468044.html
最后
以上就是知性小海豚最近收集整理的关于使用for、forin和block遍历NSArray的效率的比较的全部内容,更多相关使用for、forin和block遍历NSArray内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复