这里,NSMutableArray,NSArray和NSSet包含相同的10000000个对象.
for (Nsstring *strIn in MutableArray) //NSMutableArray{ // same Implementation}NSLog(@"Time for Mutable Array %d Iteration : %f",ObjectCount,[[NSDate date]timeIntervalSinceDate:startDate]);startDate = [NSDate date];for (Nsstring *strIn in array) //NSArray{ // same Implementation}NSLog(@"Time for NSArray %d Iteration : %f",[[NSDate date]timeIntervalSinceDate:startDate]);startDate = [NSDate date];for (Nsstring *strIn in Set) //NSSet{ // same Implementation}NSLog(@"Time for Set %d Iteration : %f",[[NSDate date]timeIntervalSinceDate:startDate]);
输出如下:
NSMutableArray 10000000迭代的时间:0.048785
NSArray 10000000迭代的时间:0.390537
NSSet 10000000迭代的时间:4.684203
为什么NSSet和NSArray迭代时间之间存在如此巨大的差异.
请仔细阅读您的答案.
编辑:
我找到了上面迭代时间背后的实际原因,因为数组和Set中的计数不等.我已经发布了实际的问题here.此外,我可以在这里发布相同的内容,但这个页面似乎太无证了,而且原因背后的原因也有偏差.再次感谢大家的回应.
#import <Foundation/Foundation.h>#define ColLECTION_SIZE 10000000static Nsstring *randomString() { unichar buffer[18]; NSUInteger size = (arc4random() % 12) + 6; for (NSUInteger i = 0; i < size; i++) { buffer[i] = (arc4random() % 93) + '!'; } return [[Nsstring alloc] initWithCharacters:buffer length:size];}static NSSet *createCollection(NSUInteger size) { NSMutableSet *collection = [[NSMutableSet alloc] init]; for (NSUInteger i = 0; i < size; i++) { for (;;) { Nsstring *s = randomString(); if (![collection member:s]) { [collection addobject:s]; break; } } } return collection;}static NSTimeInterval timedIter(ID<NSFastEnumeration> collection) { NSUInteger totalLength = 0; NSDate *startDate = [NSDate date]; for (Nsstring *s in collection) { totalLength += [s length]; } return [[NSDate date] timeIntervalSinceDate:startDate];}int main(int argc,const char **argv) { @autoreleasepool { NSSet *set = createCollection(ColLECTION_SIZE); NSArray *array = [set allObjects]; NSMutableArray *mutArray = [[set allObjects] mutablecopy]; NSLog(@"set iteration=%f",timedIter(set)); NSLog(@"array iteration=%f",timedIter(array)); NSLog(@"mutArray iteration=%f",timedIter(mutArray)); } return 0;}$clang -o itertime itertime.m -fobjc-arc -framework Foundation$./itertime2013-11-13 11:23:13.344 itertime[77576:707] set iteration=0.4225922013-11-13 11:23:13.654 itertime[77576:707] array iteration=0.3093872013-11-13 11:23:13.964 itertime[77576:707] mutArray iteration=0.309107总结
以上是内存溢出为你收集整理的ios – NSSet迭代比NSMutableArray迭代消耗更多时间,NSArray迭代比NSMutableArray迭代消耗更多时间全部内容,希望文章能够帮你解决ios – NSSet迭代比NSMutableArray迭代消耗更多时间,NSArray迭代比NSMutableArray迭代消耗更多时间所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)