出于学习目的,我试图创建自己的数组类。
所以我只是用数组创建了一个简单的类,并重载了 [] 运算符来访问类中的元素:
template <class T>
class Array
{
private:
T *arr;
int size;
public:
Array(int arrSize)
{
this->arr = new T [arrSize];
this->size = arrSize;
}
T& operator[](int pos)
{
return this->arr[pos];
}
};
当我运行一个简单的测试来检查不同容器访问其 1.000.000 个元素的速度时,我通常会得到以下结果(以秒为单位):
MyArrayClass:0.017294
C 数组:0.009943
标准::数组:0.014728
标准::向量:0.013836
为什么 C 数组比我的类快这么多?他们不是应该同样快吗?至少,考虑到它使用相同的原理来访问元素,我没想到我自己的类花费的时间是 c 数组花费的时间的两倍。
用于测量时间的代码(timenow = std::chrono::system_clock::now()):
auto ti = timenow, te=timenow;
Array<int> tst (1000000);
int tst2[1000000];
std::array<int, 1000000> tst3;
vector<int> tst4(1000000);
ArrayT tst5(1000000);
ti = timenow;
for (int i = 0; i < 1000000; i++)
{
tst[i] = 1;
}
te = timenow;
std::chrono::duration<float> et = te-ti;
cout << "MyArrayClass: " << et.count() << nl
ti = timenow;
for (int i = 0; i < 1000000; i++)
{
tst2[i] = 1;
}
te = timenow;
et = te-ti;
cout << "C Array: " << et.count() << nl
ti = timenow;
for (int i = 0; i < 1000000; i++)
{
tst3[i] = 1;
}
te = timenow;
et = te-ti;
cout << "std::array: " << et.count() << nl
ti = timenow;
for (int i = 0; i < 1000000; i++)
{
tst4[i] = i;
}
te = timenow;
et = te-ti;
cout << "std::vector: " << et.count() << nl
答案 0 :(得分:1)
我假设您提供的数字是基于优化构建的运行。
自定义 Array
可能比内置 map_Oslo.save("heat_map.html")
慢的原因有多种。我要说的一句话是,自定义数组使用堆内存,而内置数组在堆栈上。有关此主题的详细信息,请参阅 this answer。
另一个想法是在 smth 上查看生成的程序集。像godbolt.com,并比较说明。
另外,请注意您的示例正在泄漏内存 - 您在构造函数中分配但从未释放该内存。