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?
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 .
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).
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.
RTTI in OCCT consist of the following components: Early built-in RTTI implementations of C++ compilers have been considered noticeably slow.
1200 dynamic_cast
s 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:
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.
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