Before reading the question:
This question is not about how useful it is to use dynamic_cast
. Its just about its performance.
I've recently developed a design where dynamic_cast
is used a lot.
When discussing it with co-workers almost everyone says that dynamic_cast
shouldn't be used because of its bad performance (these are co-workers which have different backgrounds and in some cases do not know each other. I'm working in a huge company)
I decided to test the performance of this method instead of just believing them.
The following code was used:
ptime firstValue( microsec_clock::local_time() );
ChildObject* castedObject = dynamic_cast<ChildObject*>(parentObject);
ptime secondValue( microsec_clock::local_time() );
time_duration diff = secondValue - firstValue;
std::cout << "Cast1 lasts:" << diff.fractional_seconds() << " microsec" << std::endl;
The above code uses methods from boost::date_time
on Linux to get usable values.
I've done 3 dynamic_cast
in one execution, the code for measuring them is the same.
The results of 1 execution were the following:
Cast1 lasts: 74 microsec
Cast2 lasts: 2 microsec
Cast3 lasts: 1 microsec
The first cast always took 74-111 microsec, the following casts in the same execution took 1-3 microsec.
So finally my questions:
Is dynamic_cast
really performing bad?
According to the testresults its not. Is my testcode correct?
Why do so much developers think that it is slow if it isn't?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…