快速列举与enumerateObjectsUsingBlock
问题描述:
考虑:快速列举与enumerateObjectsUsingBlock
- (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
提供的“附加值”是什么,证明其成本合理?
答
Mattt Thompson写了一个great post on NSHipster关于迭代Objective-C的很多方法。
的附加值enumerateObjectsUsingBlock
提供的是给对象的索引和NSEnumerationOptions
:报价Mattt
enum {
NSEnumerationConcurrent = (1UL << 0),
NSEnumerationReverse = (1UL << 1),
};
typedef NSUInteger NSEnumerationOptions;
:
除非你真正需要的数字指标,而迭代,它几乎总是更快改为使用for/in NSFastEnumeration循环。
(...)
再次,快速列举几乎可以肯定是比块枚举快得多,但如果你辞职,使用块这些选项可能是有用的。
可能重复[何时使用enumerateObjectsUsingBlock与](http://*.com/questions/4486622/when-to-use-enumerateobjectsusingblock-vs-for) –