使用for、forin和block遍历NSArray的效率的比较

代码:

#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...

}

输出:

for = 326ns

forin = 237ns

block = 638ns

但是如果把所有的processNumber函数注释掉,输出的结果如下:

for = 20ns

forin = 106ns

block = 496ns

所以对于遍历数组,不能武断的得出某种方式效率一定最高的结论,实际的执行效果往往取决于代码编写的情况。

你可能感兴趣的:(NSArray)