how to determine a runtime type faster?

Daniel Keep daniel.keep.lists at gmail.com
Thu May 10 09:00:57 PDT 2007


davidl wrote:
> umm , ur way rox either. but i don't know if the cast(derive)instance is
> implemented as good as
> (instance.classinfo is derive.classinfo)?

I have a suspicion that casting is slower.

The reason is that casting doesn't simply compare the types; it has to
actually walk the object's inheritance tree.

The advantage to using cast is that... it walks an object's inheritance
tree.  Using (instance.classinfo is derive.classinfo) will NOT work if
the type of "instance" is derived from the base type.  For instance:

class A {}
class B : A {}

assert((new A).classinfo is (new B).classinfo);

The above will fail.  You should *only* directly compare them if you
really, really, REALLY need the performance, and you've actually
profiled your program to *prove* that, and you do not use inheritance at
all.

In all other cases, you should use a cast.  The only reason I didn't
suggest that in the first place is because I'm an idiot, and tried
addressing your immediate problem (the string compare) instead of the
underlying problem (checking for an instance of something).

	-- Daniel

-- 
int getRandomNumber()
{
    return 4; // chosen by fair dice roll.
              // guaranteed to be random.
}

http://xkcd.com/

v2sw5+8Yhw5ln4+5pr6OFPma8u6+7Lw4Tm6+7l6+7D
i28a2Xs3MSr2e4/6+7t4TNSMb6HTOp5en5g6RAHCP  http://hackerkey.com/



More information about the Digitalmars-d mailing list