测试环境:Visual Studio 2008 SP1
测试对象:RTTI的dynamic_cast和自己实现的RTTI系统,代码如下
template<typename TClass>
TClass* Cast( )
{
return IsKindOf( TClass::StaticGetClassInfo() ) ? (TClass*)this:null;
}
bool RTTIObject::IsKindOf( RTTIClass* ClassInfo )
{
RTTIClass* ThisClass = GetRTTIClass();
if ( ThisClass == null )
return false;
return ThisClass->IsKindOf( ClassInfo );
}
bool RTTIClass::IsKindOf( RTTIClass* ClassInfo )
{
RTTIClass* ThisClass = this;
while ( ThisClass != null )
{
if ( ClassInfo == ThisClass )
return true;
ThisClass = ThisClass->mParentClass;
}
return false;
}
测试代码:
class ClassA : public RTTIObject
{
public:
DECLARE_RTTI_CLASS( ClassA )
int a;
private:
};
IMPLEMENT_RTTIROOT( ClassA )
class ClassB: public ClassA
{
DECLARE_RTTI_CLASS( ClassB )
public:
int b;
private:
};
IMPLEMENT_RTTI_CLASS( ClassB, ClassA )
class ClassC : public ClassB
{
DECLARE_RTTI_CLASS( ClassC )
public:
int c;
private:
};
IMPLEMENT_RTTI_CLASS( ClassC, ClassB )
class ClassD: public ClassA
{
DECLARE_RTTI_CLASS( ClassD )
public:
int d;
private:
};
ClassC c;
ClassD d;
ClassA* fakeC = &c;
ClassA* fakeD = &d;
const int TestTimes = 10000;
float t1 = TimeSource::GetAppTime();
for ( int i = 0;i<TestTimes;i++)
{
ClassC* realC = dynamic_cast<ClassC*>(fakeC);
ClassD* realD = dynamic_cast<ClassD*>(fakeD);
}
float t2 = TimeSource::GetAppTime() - t1;
for ( int i = 0;i<TestTimes;i++)
{
ClassC* realC = fakeC->Cast<ClassC>( );
ClassD* realD = fakeD->Cast<ClassD>( );
}
float t3 = TimeSource::GetAppTime() - t2;
SimpleLog log;
log.Debug(L"%f %f", t2, t3);
10000次,单位:毫秒 |
dynamic_cast |
Cast |
Debug |
1.468590 |
5.173067 |
Release |
1.025950 |
0.702404 |
可以看得出来,没有优化过的Cast代码性能极差,但是优化过的Cast性能超越了系统的dynamic_cast,跟踪汇编发现系统有做个一些异常及bad_cast的处理
建议:可以做一个宏,在不支持RTTI的编译器及平台下使用自己的Cast