Hello,
I'm using a library which creates allows me to set void* userData for some of it's objects, so I can connect their objects with mine. When an event happens I get their object and I can retrieve my class from it using casting. My question is about the performance of my approach. So this is the setup.
// This is library class I get
struct Collision { void* userData;};
// My base class
struct Vehicle { };
// My derived class
struct Plane: Vehicle { void Fly(){} };
// My instances
Vehicle v;
Plane p;
// Thier instances
Collision a; a.userData = &v;
Collision b; b.userData = &p;
Collision c; c.userData = NULL;
// This is where I want to get to plane
void EventCallBack(Collision& col)
{
// Make sure it's not c
if(!col.userData) return;
// I know for sure this will succeed
Vehicle* v = static_cast<Vehicle*>(col.userData);
// Try and see if it's acutally a plane type
Plane* p = dynamic_cast<Plane*>(v);
// If it's make it fly
if(p) p->Fly();
}
I know that dynamic_cast is slow. Another way to do that is to introduce a virtual function into Vehicle, but that does not make sense, because Fly() is required only by Planes.
Yet another approach is to have a variable in Vehicle that says what type of the object it is. The question is: Is dynamic_cast that slow so it justifies using some other approach? Let's say if we have a 6000 calls to this function per second.
Thanks.