wacko wrote:I do not know where you got your info on the cost of dynamic_cast but its costly. The code i wrote above is 20x faster if you just use the GetType functionality of the virtual call than using dynamic_cast. It has to walk the entire class hierarchy, which includes dealing with crap like virtual tables, multiple inheritance, possible ambiguities in base objects and its even worse on 64bit systems. to do a dynamic_cast is an O(n) operation when it comes to inheritance hierarchy, which is not the case for the virtual function. Sure in some cases where its a very special one off case I could see using dynamic_cast/RTTI but if correctly architected you should not need to do anything like that and in this posters case I think the best option is something like the one I posted above.
So now we're talking about performance, instead of you saying that using dynamic_cast<> is
poor programming practice and leads to
buggy code. Wait, where was that? Oh yeah:
wacko wrote:I think what your advocating is a poor programming practice and leads to buggy code [...]
Also:
wacko wrote:[...] there was a reason why it was not in the lang to begin with and thats because people use it incorrectly.
Explain: how did people use it incorrectly
if it wasn't in the language? I digress.
Okay, so performance it is.
Are we talking about an ambiguous multi-level heirarchy, then?
20 times faster seems a bit of a reach, say, for one heirarchy level. Is this comparison in an unoptimized compile? Certainly dynamic_cast<> is capable of tens of millions of these per second. It would be a fun exercise to test this on a couple of compilers, maybe gcc and Visual.
If there are more levels of heirarchy to walk through, it does become a big deal. I'm wondering about the context of the test, though.
I don't know if you would do a lot of cast tests in the context of most games, and I mean per frame. It seems you would aim to segment your different objects to gain more natural optimization benefits and avoid the casts for the most part. Usually cast tests happen in a collision or some special event that one object needs to know the type, as well as the identity, of the event objects. On the other hand, if you had to go through a thousand dynamic_cast<> operations every frame, you might see a couple of milliseconds wasted, and yes, that could be a serious expenditure.
I wouldn't be so concerned with dynamic_cast<> performance until you have a little bit of volume, but that's true about any optimization. I wouldn't put in extra code if RTTI can handle it in small volume.
In any event, Mr. Stroustrup would be so unhappy if he found out his operator was advocating bad programming practice!