for VS for(... in ...)
NSMutableArray *test = [NSMutableArray array];
for (int i= 0; i < 10000000; i++) {
[test addObject:@(i)];
}
int sum = 0;
double date_s = CFAbsoluteTimeGetCurrent();
for (int i = 0;i < test.count; i++) {
sum += 1;
}
double date_e = CFAbsoluteTimeGetCurrent();
NSLog(@"ForLoop Time: %f", date_e - date_s);
date_s = CFAbsoluteTimeGetCurrent();
for (id obj in test) {
sum += 1;
}
date_e = CFAbsoluteTimeGetCurrent();
NSLog(@"Enumeration Time: %f", date_e - date_s);
NSMutableArray *test = [NSMutableArray array];
for (int i= 0; i < 10000000; i++) {
[test addObject:@(i)];
}
int sum = 0;
double date_s = CFAbsoluteTimeGetCurrent();
for (int i = 0;i < test.count; i++) {
int key = [test[i] intValue];
sum += key;
sum -= key;
}
double date_e = CFAbsoluteTimeGetCurrent();
NSLog(@"ForLoop Time: %f", date_e - date_s);
date_s = CFAbsoluteTimeGetCurrent();
for (id obj in test) {
int key = [obj intValue];
sum += key;
sum -= key;
}
date_e = CFAbsoluteTimeGetCurrent();
NSLog(@"Enumeration Time: %f", date_e - date_s);
enumerateObjectsUsingBlock VS for(... in ...)
for(... in ...)用起来非常方便、简洁,同时
enumerateObjectsUsingBlock:
也有很多新特性:
-
通常enumerateObjectsUsingBlock:
和 (for(... in ...)在效率上基本一致,有时会快些。主要是因为它们都是基于
NSFastEnumeration
实现的. 快速迭代在处理的过程中需要多一次转换,当然也会消耗掉一些时间. 基于Block的迭代可以达到本机存储一样快的遍历集合. 对于字典同样适用,而数组的迭代却不行。
-
注意"enumerateObjectsUsingBlock" 修改局部变量时, 你需要声明局部变量为 __block 类型
.
-
enumerateObjectsWithOptions:usingBlock:
支持并发迭代或反向迭代,并发迭代时效率也非常高.
-
对于字典而言, enumerateObjectsWithOptions:usingBlock
也是唯一的方式可以并发实现恢复Key-Value值.
就个人而言, 我偏向于使用 enumerateObjectsUsingBlock:
当然最后还是要根据实际情况上下文决定用什么
NSMutableArray *test = [NSMutableArray array];
for (int i= 0; i < 10000; i++) {
[test addObject:@(i)];
}
double date_s = CFAbsoluteTimeGetCurrent();
for (id obj in test) {
NSLog(@"%@",obj);
}
double date_e = CFAbsoluteTimeGetCurrent();
NSLog(@"ForLoop Time: %f", date_e - date_s);
date_s = CFAbsoluteTimeGetCurrent();
// [test enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
// NSLog(@"%@",obj);
// }];
[test enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(@"%@",obj);;
}];
date_e = CFAbsoluteTimeGetCurrent();
NSLog(@"Enumeration Time: %f", date_e - date_s);
// ForLoop Time: 14.951485
// Default Enumeration Time: 14.702673
// Reverse Enumeration Time: 14.948526
// Concurrent Enumeration Time: 10.056317