在我对一千万成员的测试条件下,我发现第二种方法,简单循环更快——0 秒对 32 秒。拥有 100 万会员的时间是 0 秒对 3 秒。这确实假设所有数据都在内存中,并且与 Rob Napier 的经验一致。这是测试代码:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
NSMutableSet *testSet = [NSMutableSet set];
int i = 0;
while (i <10000000) {
[testSet addObject:[[TestObjects alloc] init]];
i++;
}
NSLog(@"%@",[NSDate date]);
NSNumber* sum = [testSet valueForKeyPath:@"@sum.myProperty"];
NSLog(@"%@",[NSDate date]);
NSLog(@"%@",sum);
NSLog(@"%@",[NSDate date]);
long long sum2 = 0;
for(TestObjects *obj in testSet)
sum2 += obj.myProperty;
NSLog(@"%@",[NSDate date]);
NSLog(@"%lld",sum2);
NSLog(@"%ld",testSet.count);
}
而 TestObject 在 init 中只有这个:
-(id)init {
if (self = [super init]) {
self.myProperty = arc4random() %100;
}
return self;
}