Game Development Community

Should I be afraid of Type Casting? :p

by Stefan Lundmark · in Torque Game Engine · 09/02/2006 (9:35 am) · 3 replies

I have heard horror stories of dynamic_cast and that you should never use it in a performance situation. So then we have static_cast which is said to be alot lighter in that it does not check if the types are correct.

I am modifying the mount system in Torque to accept GameBase objects instead of only ShapeBase ones. For this to work, I need to static_cast in renderMountPosition() from GameBase to the derived class, be it Player or Vehicle or whatever.

Is this wise, considering that renderMountPosition() is called on each tick for every object out there, perhaps even each frame?

I stuffed the following into guiShapeNameHud::onRender() to see if I could spot a difference:

for ( int i = 0; i < 1000000000; i++ )
{
ShapeBase* object = static_cast<ShapeBase*>(*itr);
}

Fps went down from 333 to 328. No big deal, that's alot of loops.
If I check the profiler log though, guiShapeNameHud just climbed to the 5th place, from 14th.

Still, these stories scare the heck out of me and I keep wondering if I should go ahead, or if it will stab me in the back later on. Any suggestions?

#1
09/02/2006 (9:47 am)
I'd say don't let it halt development. Make note of it and go on. You can look at it again when optimizing.

That said, is there a place in the code where you can do the casting elsewhere outside of the loop?
If the casting won't affect other functions, maybe cast it when object is created or at some other less intensive time?
#2
09/02/2006 (9:51 am)
Nevermind the last part of my post. after thinking about it, it was a dumb idea.
#3
09/02/2006 (1:51 pm)
@Stefan - Remember static_cast<> pretty much evaluates to nothing... it's just compile time, so your test is just testing the loop cost. dynamic_cast<> has to, at run-time, traverse the hierarchy of type info for that particular class instance looking for the cast class. In the best case it's already of that type and returns after one check. Worst case it isn't of that type and has to traverse the hierarchy completely. If you have an object with a deep base class hierarchy then this could be alot of checks.

In your case if it's not a vehicle then your checking all the way up the class hierarchy... i would assume this happens a lot more than it not being a player. This leads to one minor improvement... check to see if it's a player first and it will early out most of the time.

Still consider that the time to do a dynamic_cast<> is still measured in nanoseconds. Unless your doing thousands per frame then i wouldn't worry too much.