都说dynamic_cast等动态类型识别效率不高。现编写一段代码,实际测一下。剖分代码源于网络
class Derived : public Base
{
public:
virtual void show() {};
};
int main()
{
Base* pBase = new Derived();
Derived* pDerived = NULL;
time_t begin, end;
begin = time(NULL);
for(int i=0; i < 100000; ++i) // 10W次
{
pDerived = dynamic_cast<Derived * >(pBase);
}
end = time(NULL);
cout << "seconds: " << end-begin << endl;
cout << typeid( *pDerived ).name() << endl;
cout << typeid(pDerived ).name() << endl;
system("pause");
return 0;
}
seconds: 0
seconds: 5
class Derived
class Derived *
看了一下dynamic_cast和typeid的汇编指令,
每个都有至少几百条指令。毕竟要”traverse the class derivation lattice of its argument at runtime“
我又测了虚函数方法,代码结果如下
class Derived : public Base
{
public:
int GetType();
virtual void show() {};
};
int Derived::GetType()
{
return 9;
}
int main()
{
Base* pBase = new Derived();
time_t begin, end;
begin = time(NULL);
Derived * p;
for (int i=0; i<100000000; ++i)
{
if (pBase->GetType() == 9)
{
p = (Derived *)(pBase);
}
}
end = time(NULL);
cout << "seconds: " << end-begin << endl;
system("pause");
return 0;
}
seconds: 3
处理亿数量级的问题,无论采用什么动态类型方法,都会慢的。因为要调用亿次函数。
如下代码,调用了Add方法1亿次。
class Derived : public Base
{
public:
int GetType();
virtual void show() {};
};
int Derived::GetType()
{
return 9;
}
int Add(int i, int j)
{
return i;
}
int main()
{
Base* pBase = new Derived();
time_t begin, end;
begin = time(NULL);
Derived * p;
for (int i=0; i<100000000; ++i)
{
//if (pBase->GetType() == 9)
//{
//p = (Derived *)(pBase);
//}
Add(1,2);
}
end = time(NULL);
cout << "seconds: " << end-begin << endl;
system("pause");
return 0;
}
seconds: 3
综合对比来看,dynamic_cast效率还是不错的。可见,估算效率不能只“想想”,要实际测试一下。