I know that dynamic_cast have runtime check and therefor consider safer (can return null pointer on failure) but slower then static_cast. but how bad is the overhead between the two?
should I realy consider use static_cast in loops for performance issues in regular large projects? or the difference is minor and only relevant for special real-time programs.
dynamic_cast runs at about 14.4953 nanoseconds. Checking a virtual method and static_cast ing runs at about twice the speed, 6.55936 nanoseconds.
The dynamic_cast operator ensures that if you convert a pointer to class A to a pointer to class B , the object of type A pointed to by the former belongs to an object of type B or a class derived from B as a base class subobject.
The cost of a dynamic_cast will therefore be that of calling a virtual method, loading the type info, and iterating over a contiguous region of memory.
In C++, dynamic casting is mainly used for safe downcasting at run time. To work on dynamic_cast there must be one virtual function in the base class. A dynamic_cast works only polymorphic base class because it uses this information to decide safe downcasting.
Did you profile it?
The rule is:
static_cast
when you know that the target type is valid.dynamic_cast
when you're not sure, and you need the program to look up the object's runtime type for you.It's as simple as that. All other considerations are secondary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With