Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic_cast overhead in C++

Tags:

c++

casting

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.

like image 402
Aviv A. Avatar asked Sep 08 '11 14:09

Aviv A.


People also ask

Is dynamic_cast fast?

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.

What is the use of dynamic_cast operator?

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.

Is dynamic cast expensive?

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.

Why dynamic_cast is used in C++?

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.


1 Answers

Did you profile it?

The rule is:

  • Use static_cast when you know that the target type is valid.
  • Use 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.

like image 129
Lightness Races in Orbit Avatar answered Nov 06 '22 12:11

Lightness Races in Orbit