Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How fast is dynamic_cast<>

... approximately compared to a typical std::string::operator==()? I give some more details below, I'm not sure if they are of any relevance. Answer with complexity or approximation is good enough. Thanks!

Details: I will use it inside a for loop over a list to find some specific instances. I estimate my average level of inheritance to 3.5 classes. The one I'm looking for has a parent class, a grandparent and above that two "interfaces", i.e. to abstract classes with a couple of virtual void abc() = 0;.

There is no sub-class to the one I'll be looking for.

like image 420
Jonas Byström Avatar asked Mar 19 '12 21:03

Jonas Byström


People also ask

Is Static_cast faster than dynamic_cast?

If performance of dynamic_cast is an issue in your application, you should reconsider the design. While typeid + static_cast is faster than dynamic_cast , not having to switch on the runtime type of the object is faster than any of them. Show activity on this post.

When should I use dynamic_cast?

dynamic_cast −This cast is used for handling polymorphism. You only need to use it when you're casting to a derived class. This is exclusively to be used in inheritence when you cast from base class to derived class.

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 .

Does dynamic_cast use RTTI?

For example, dynamic_cast uses RTTI and the following program fails with the error “cannot dynamic_cast `b' (of type `class B*') to type `class D*' (source type is not polymorphic) ” because there is no virtual function in the base class B.


1 Answers

It depends hugely on your compiler, your particular class hierarchy, the hardware, all sorts of factors. You really need to measure it directly inside your particular application. You can use rdtsc or (on Windows) QueryPerformanceCounter to get a relatively high-precision timer for that purpose. Be sure to time loops or sleds of several thousand dynamic_cast<>s, because even QPC only has a ¼μs resolution.

In our app, a dynamic_cast<> costs about 1 microsecond, and a string comparison about 3ns/character.

Both dynamic_cast<> and stricmp() are at the top of our profiles, which means the performance cost of using them is significant. (Frankly in our line of work it's unacceptable to have those functions so high on the profile and I've had to go and rewrite a bunch of someone else's code that uses them.)

like image 127
Crashworks Avatar answered Oct 03 '22 09:10

Crashworks