jmasterx
jmasterx

Reputation: 54173

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?

Upvotes: 33

Views: 14833

Answers (3)

Ben Voigt
Ben Voigt

Reputation: 283793

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.

Upvotes: 31

zdan
zdan

Reputation: 29460

In this particular circumstance, you should be able to organise your code so that the dynamic_cast is only needed once. I imagine that the backend in not changing dynamically.

Upvotes: -1

Joris
Joris

Reputation: 6306

Can't you define your own cast using a #define, which uses dynamic_cast in debug build (so you know your cast is correct) and does a simple (MySubclass *) cast in release build so there is no performance cost?

Upvotes: -1

Related Questions