我有一个序列式内存二维数组的类,最初是一个 int
类型的数组。现在我需要一个类型相似的数组,但存储的对象类型不同,因此我使用了模板重写了这个类;唯一的区别就在于存储对象的类型:
template <class T>
class Serial2DArray
{
...
T ** Content;
}
我有一些处理内容的测试函数,例如将数组中所有元素置空的函数(它们不是类成员,而是用于与
Serial2DArray<int>
对象一起工作的函数)。我注意到现在它的速度变慢了1-2%——类中的所有其他代码都没有改变,唯一的区别是以前它只是一个带有int ** Content
的普通类,现在它是一个模板。类似的问题:C++模板会使程序变慢吗? - 有人认为仅编译变慢(我能看出来,编译器为其在代码中找到的每个类型生成类),但我看到程序在运行时变慢了——是否有任何合理的解释?
更新:问题在此处被缩小了一点:https://stackoverflow.com/a/11058672/1200000 更新2:如评论所述,下面是变慢的函数:
#include <windows.h>
#include <mmsystem.h>
...
int Size = G_Width * G_Height * sizeof(int);
DWORD StartTime = timeGetTime();
for(int i=0; i<100; ++i)
{
FillMemory(TestArray.Content[0], Size, 0);
}
MeasuredTime = timeGetTime() - StartTime;
这里是实际的类模板:
#include <malloc.h>
template <class T>
class Serial2DArray
{
public:
Serial2DArray()
{
Content = NULL;
Width = 0;
Height = 0;
}
Serial2DArray(int _Width, int _Height)
{
Initialize(_Width, _Height);
}
~Serial2DArray()
{
Deinitialize();
}
T ** Content;
int GetWidth()
{
return Width;
}
int GetHeight()
{
return Height;
}
int Initialize(int _Width, int _Height)
{
// creating pointers to the beginning of each line
if((Content = (T **)malloc(_Height * sizeof(T *))) != NULL)
{
// allocating a single memory chunk for the whole array
if((Content[0] = (T *)malloc(_Width * _Height * sizeof(T))) != NULL)
{
// setting up line pointers' values
T * LineAddress = Content[0];
for(int i=0; i<_Height; ++i)
{
Content[i] = LineAddress; // faster than Content[i] =
LineAddress += _Width; // Content[0] + i * _Width;
}
// everything went ok, setting Width and Height values now
Width = _Width;
Height = _Height;
// success
return 1;
}
else
{
// insufficient memory available
// need to delete line pointers
free(Content);
return 0;
}
}
else
{
// insufficient memory available
return 0;
}
}
int Resize(int _Width, int _Height)
{
// deallocating previous array
Deinitialize();
// initializing a new one
return Initialize(_Width, _Height);
}
int Deinitialize()
{
// deleting the actual memory chunk of the array
free(Content[0]);
// deleting pointers to each line
free(Content);
// success
return 1;
}
private:
int Width;
int Height;
};
根据要求,提供二进制文件大小比较。
代码如下:
Serial2DArray<int> TestArray;
Serial2DArray<int> ZeroArray;
- 1,016,832字节。
使用以下代码:
Serial2DArray TestArray; // NOT-template class with ints
Serial2DArray ZeroArray; // methods are in class declaration
- 1 016 832字节
使用以下代码:
Serial2DArray<int> TestArray;
Serial2DArray<int> ZeroArray;
Serial2DArray<double> AnotherArray;
Serial2DArray<double> YetAnotherArray;
- 1,017,344字节