gpt4 book ai didi

ios - NSSet Iteration 比 NSMutableArray Iteration 消耗更多时间,NSArray Iteration 比 NSMutableArray Iteration 消耗更多时间

转载 作者:可可西里 更新时间:2023-11-01 05:35:53 27 4
gpt4 key购买 nike

尽管如此,我遍历了以下 NSSet , NSMutableArray , NSFastEnumeration文档,我找不到下面提到的场景的令人满意的来源:

此处,NSMutableArrayNSArrayNSSet 均包含 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",ObjectCount,[[NSDate date]timeIntervalSinceDate:startDate]);
startDate = [NSDate date];
for (NSString *strIn in Set) //NSSet
{
// same Implementation
}
NSLog(@"Time for Set %d Iteration : %f",ObjectCount,[[NSDate date]timeIntervalSinceDate:startDate]);

输出如下:

NSMutableArray 10000000 次迭代的时间:0.048785

NSArray 10000000 次迭代的时间:0.390537

NSSet 10000000 次迭代的时间:4.684203

为什么 NSSetNSArray 迭代时间有这么大的差异。

请彻底回答你的问题。

编辑:我已经找到了上述迭代时间背后的实际原因,这是因为 array 和 Set 中的计数不相等。我已经发布了实际问题 here .另外,我可以在这里发布相同的内容,但对于此页面来说,它似乎太过无证性质,而且原因背后的原因也有偏差。再次感谢大家的回复。

最佳答案

我不同意你的结果:

#import <Foundation/Foundation.h>

#define COLLECTION_SIZE 10000000

static 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
$ ./itertime
2013-11-13 11:23:13.344 itertime[77576:707] set iteration=0.422592
2013-11-13 11:23:13.654 itertime[77576:707] array iteration=0.309387
2013-11-13 11:23:13.964 itertime[77576:707] mutArray iteration=0.309107

关于ios - NSSet Iteration 比 NSMutableArray Iteration 消耗更多时间,NSArray Iteration 比 NSMutableArray Iteration 消耗更多时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19951524/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com