for VS for(... in ...)
- for 的應用范圍廣基本可以NSArray、NSArray以及C語言的數組等,而for(... in ...)僅限於NSArray、NSArray等
- for(... in ...) 更簡潔、效率更高
測試代碼:
10^7 的數組,時間單位 秒,精確度 毫秒
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);
測試結果:

考慮到實際情況,ForLoop 的操作較多些。
測試代碼:
硬件:i5 Cpu, 10G 內存,Mac OS X 10.9.4
數據量:10^7 的數組,
時間:單位 秒,精確度 毫秒
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: 當然最后還是要根據實際情況上下文決定用什么
測試代碼:
硬件:i5 Cpu, 10G 內存,Mac OS X 10.9.4
數據量:10^4 的數組,執行一次NSLog輸出
時間:單位 秒,精確度 毫秒
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
參考:
http://stackoverflow.com/questions/4486622/when-to-use-enumerateobjectsusingblock-vs-for
