考虑:
- (void) testing {
NSMutableArray * numbers = [NSMutableArray arrayWithCapacity:10000000] ;
for (int i = 0 ; i < 10000000 ; ++i) {
[numbers addObject:@(i)] ;
}
NSInteger (^sum)(NSInteger, NSInteger) = ^(NSInteger running, NSInteger n) {
return running + n ;
} ;
double start = ::CACurrentMediaTime() ;
__block NSInteger running = 0 ;
for (NSNumber * n in numbers) {
running = sum(running, [n integerValue]) ;
}
running = 0 ;
double end1 = ::CACurrentMediaTime() ;
[numbers enumerateObjectsUsingBlock:^(NSNumber * n, NSUInteger idx, BOOL *stop) {
running = sum(running, [n integerValue]) ;
}] ;
double end2 = ::CACurrentMediaTime() ;
::NSLog(@"fastEnum: %0.3f, enumUsingBlock: %0.3f", end1-start, end2-end1) ;
}
这输出:
2013-08-05 00:38:34.852 WC[48299:a0b] fastEnum: 0.341, enumUsingBlock: 1.358
这表示这enumerateObjectsUsingBlock
比常规迭代慢 4 倍左右。
什么时候使用其中一种?enumerateObjectsUsingBlock
证明其成本合理的“附加价值”是什么?