Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How expensive are dynamic casts in C++?

For my GUI API which works with a variety of backends (sdl, gl, d3d, etc) I want to dynamically cast the generic type image to whatever it may happen to be.

So the bottom line is, I would be doing around 20 * 60fps dynamic casts per second.

How expensive is a dynamic cast? Will I notice that it has a noticeable negative impact on performance? What alternatives do I have that still maintain an acceptable level of performance?

like image 685
jmasterx Avatar asked Apr 17 '11 15:04

jmasterx


People also ask

Is dynamic cast a code smell?

Yes, dynamic_cast is a code smell, but so is adding functions that try to make it look like you have a good polymorphic interface but are actually equal to a dynamic_cast i.e. stuff like can_put_on_board .

What is dynamic cast in C?

A cast is an operator that forces one data type to be converted into another data type. In C++, dynamic casting is, primarily, used to safely downcast; i.e., cast a base class pointer (or reference) to a derived class pointer (or reference).

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.

Is Rtti slow?

RTTI in OCCT consist of the following components: Early built-in RTTI implementations of C++ compilers have been considered noticeably slow.


1 Answers

1200 dynamic_casts per second is not likely to be a major performance problem. Are you doing one dynamic_cast per image, or a whole sequence of if statements until you find the actual type?

If you're worried about performance, the fastest ways to implement polymorphism are:

  • --- fastest ---
  • Function overloading (compile-time polymorphism only)
  • CRTP (compile-time polymorphism only)
  • Tags, switches and static casts (brittle, doesn't support multi-level inheritance, a maintenance headache so not recommended for unstable code)
  • Virtual functions
  • Visitor pattern (inverted virtual function)
  • --- almost as fast ---

In your situation, the visitor pattern is probably the best choice. It's two virtual calls instead of one, but allows you to keep the algorithm implementation separate from the image data structure.

like image 173
Ben Voigt Avatar answered Sep 25 '22 02:09

Ben Voigt