zoukankan      html  css  js  c++  java
  • 使用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

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

  • 相关阅读:
    【hive】null值判断
    【hive】where使用注意的问题
    【hive】关于浮点数比较的问题
    【hive】在alter修改元数据的时候报错 mismatched input 'xxxxx' expecting KW_EXCHANGE
    破解诅咒心法
    泡妞心法
    awk高级
    排除故障的总结
    机房运维相关面试题
    统计流入流出流量
  • 原文地址:https://www.cnblogs.com/xwoder/p/4468044.html
Copyright © 2011-2022 走看看