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:\t" << 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?
rain herring in Iceland tonight
. Compilable code is king. PS.Most casting would be implicit (passing a child object to a function that takes a parent (pointer/reference)). PPS. What are you comparing it against? – Kearethe following casts
. So essentially Cast2 is the same test performed a second time. Cast3 is the same performed a 3rd time. – Reimer