我设置了一个(可能非常不科学)小测试来确定单级单继承中虚函数的开销,我得到的结果在多态访问派生类或直接访问派生类时完全一样。有点令人惊讶的是当任何函数被声明为虚拟时引入的计算时间的数量级(见下面的结果)。
声明成员函数时是否有这么多开销,为什么即使直接访问派生类仍然存在?
代码如下:
class base
{
public:
virtual ~base() {}
virtual uint func(uint i) = 0;
};
class derived : public base
{
public:
~derived() {}
uint func(uint i) { return i * 2; }
};
uint j = 0;
ulong k = 0;
double l = 0;
ushort numIters = 10;
base* mybase = new derived; // or derived* myderived = ...
for(ushort i = 0; i < numIters; i++)
{
clock_t start2, finish2;
start2 = clock();
for (uint j = 0; j < 100000000; ++j)
k += mybase->func(j);
finish2 = clock();
l += (double) (finish2 - start2);
std::cout << "Total duration: " << (double) (finish2 - start2) << " ms." << std::endl;
}
std::cout << "Making sure the loop is not optimized to nothing: " << k << std::endl;
std::cout << "Average duration: " << l / numIters << " ms." << std::endl;
结果:
base* mybase = new derived;
平均约为 338 毫秒。
derived* myderived = new derived;
平均约为 338 毫秒。
消除继承和删除虚函数平均为 38 毫秒。
这几乎少了10倍!所以基本上,如果任何函数被声明为虚拟,即使我不以多态方式使用它,开销也将始终相同?
谢谢。