平时用dynamic_cast,但是一直没有考虑过性能。但是性能怎么样,还真没想过。下测试就是一段测试程序,在linux下跑。
循环2亿次,用dynamic_cast<XTestEx *>()的时候是2.39978秒,用(XTestEx *)直接转的时间是0.723503秒。如果加上附加代码带来的误差。dynamic_cast<XTestEx *>()费时是(XTestEx *)的近4倍.但总的来说,性能影响不大!
#include <iostream>#include<sys/time.h>
using namespace std;
class XTestBase
{
public:
virtual ~XTestBase(){}
virtual int getValue() = 0;
};
class XTestEx : public XTestBase
{
public:
virtual ~XTestEx(){}
virtual int getValue()
{
return 100;
}
};
int main(int argc, char * argv[])
{
struct timeval st1,st2;
XTestBase * pB = new XTestEx();
int iC = 0;
gettimeofday(&st1, NULL);
for(int i = 0; i < 200000000; i++)
{
XTestEx * p = dynamic_cast<XTestEx *>(pB);
iC += p->getValue();
}
gettimeofday(&st2, NULL);
long long diff = 1000000ll * (st2.tv_sec-st1.tv_sec)+ st2.tv_usec-st1.tv_usec;
cout<<"diff:"<<(diff/1000000.0)<<endl;
gettimeofday(&st1, NULL);
for(int i = 0; i < 200000000; i++)
{
XTestEx * p = (XTestEx *)pB;
iC += p->getValue();
}
gettimeofday(&st2, NULL);
diff = 1000000ll * (st2.tv_sec-st1.tv_sec)+ st2.tv_usec-st1.tv_usec;
cout<<"diff:"<<(diff/1000000.0)<<endl;
return 0;
}