for,for-in和enumerateObjectsUsingBlock的比较

本文探讨了Objective-C中三种遍历集合的常见方法:for循环、for-in循环和enumerateObjectsUsingBlock,并通过实例比较了它们在遍历NSArray和字典时的效率与代码优雅性。在仅遍历数组的情况下,for-in表现最佳;而在遍历字典时,enumerateObjectsUsingBlock不仅速度快,而且代码更加清晰直观。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天在敲代码是碰见了enumerateObjectsUsingBlock,忽然就想比较一下他们的区别,闲话少说,开始吧


1.关于for这个方法,可以说接触到c语言是必须掌握的,for的应用范围很广,基本可以NSArray,NSMutableArray以及C语言的数组等,太过简单,我就不说了

2.for-in局限于NSArray,NSMutableArray等,但是它效率高,而且简洁,今天的话我们主要比较for-in和enumerateObjectsUsingBlock


(1)便利一个数组,看三个方法谁更快


当只是遍历一个数组的时候使用For-in最快, 推荐使用For-in遍历数组.


(2)通过value查找index

    NSMutableArray *test = [NSMutableArray array];
    for (NSInteger i = 0; i < 10000000; i ++) {
        [test addObject:@(i + 10)];
    }
    
    //For-in
    __block NSInteger index = 0;
    double date_s = CFAbsoluteTimeGetCurrent();
    for (NSNumber *num in test) {
        if ([num integerValue] == 9999999) {
            index = [test indexOfObject:num];
            break;
        }
    }
    double time = CFAbsoluteTimeGetCurrent() - date_s;
    NSLog(@"index : %ld For-in 时间: %f ms",(long)index,time * 1000);
    
    //enumerateObjectsUsingBlock
    index = 0;
    date_s = CFAbsoluteTimeGetCurrent();
    [test enumerateObjectsUsingBlock:^(id num, NSUInteger idx, BOOL *stop) {
        if ([num integerValue] == 9999999) {
            index = idx;
            *stop = YES;
        }
    }];
    time = CFAbsoluteTimeGetCurrent() - date_s;
    NSLog(@"index : %ld enumerateBlock 时间: %f ms",(long)index,time * 1000);
    
    //enumerateObjectsWithOptions
    index = 0;
    date_s = CFAbsoluteTimeGetCurrent();
    [test enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id num, NSUInteger idx, BOOL *stop) {
        if ([num integerValue] == 9999999) {
            index = idx;
            *stop = YES;
        }
    }];
    time = CFAbsoluteTimeGetCurrent() - date_s;
    NSLog(@"index : %ld enumerateObjectsWithOptions 时间: %f ms",(long)index,time * 1000);

通过value查找index的时候,面对大量的数组推荐使用enumerateObjectsWithOptions方法,但我比较喜欢使用

enumerateObjectsUsingBlock方法,简洁明了

(3)遍历字典比较for-in和enumerateObjectsUsingBlock


当我们想遍历字典类型的时候, 推荐使用enumerateObjectsUsingBlock
不仅仅是因为速度快, 更是因为代码更优雅和直观.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值