【发布时间】:2011-06-07 13:59:27
【问题描述】:
我来自 C++/STL 世界,我想检查一下 Objective-c 容器与 stl 相比如何。
我想比较一个数字数组,但将数字添加到 NSArray 的唯一方法是使用 NSNumber,这非常慢并且我的 ram 是空的,所以我想我需要手动释放它们。但我不想测试副作用,所以我只是将[NSNull null] 添加到数组中。
将 10k 个东西添加到数组中 1k 次的结果:NSArray - 0.923411 秒vector<int> - 0.129984 秒
我认为这可能是分配和释放,所以我将数组的数量(代码中的imax)设置为 1,将添加的数量设置为 10000000(jmax),但速度更慢NSArray - 2.19859 秒vector<int> - 0.223471 秒
编辑:
正如 cmets 中提到的,数组的不断增加的大小可能是问题,所以我使用arrayWithCapacity 制作了NSArray,但vector 也使用了reserve,它甚至比以前慢(!)(imax = 1,jmax = 10000000)。NSArray - 2.55942vector<int> - 0.19139
结束编辑
为什么这么慢?
我的代码供参考:
#import <Foundation/Foundation.h>
#include <vector>
#include <iostream>
#include <time.h>
using namespace std;
int main (int argc, const char * argv[])
{
int imax = 1000;
int jmax = 10000;
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
cout << "Vector insertions" << endl;
clock_t start = clock();
for(int i = 0; i < imax; i++)
{
vector<int> *v = new vector<int>();
for(int j = 0; j < jmax; j++)
{
v->push_back(j);
}
delete v;
}
double interval = (clock() - start) / (double)CLOCKS_PER_SEC;
cout << interval << " seconds" << endl;
cout << "NSArray insertions" << endl;
start = clock();
for(int i = 0; i < imax; i++)
{
NSMutableArray *v = [[NSMutableArray alloc] init];
for(int j = 0; j < jmax; j++)
{
[v addObject:[NSNull null]];
}
[v dealloc];
}
interval = (clock() - start) / (double)CLOCKS_PER_SEC;
cout << interval << " seconds" << endl;
[pool drain];
return 0;
}
【问题讨论】:
-
如果你想快速存储整数,为什么不使用 C 数组?
-
存储任何东西,即使是空值也会慢 10 倍
标签: objective-c optimization stl