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