今天在敲代码是碰见了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
不仅仅是因为速度快, 更是因为代码更优雅和直观.