(C#) how much does is-test cost?

  • Thread starter Thread starter Dmitry Martynov
  • Start date Start date
D

Dmitry Martynov

Consider I have the following construction "if(x is T) ...". How much this
test cost? And I wonder how it is implemented. Can I gain in performace if I
introduce virtual methods like "bool isIt...()" in my base class and then
call them instead of using is-operator?
 
is test isn't inherently expensive except after the test when you need to
actually go ahead and make the conversion. This is repetitive since the is
check already performed the conversion but only returned a bool result.

Consider x is int; actually tests to see whether (int)x type is valid and
will complete without throwing. User defined conversions aren't considered.

Now if you must use x lower down, this is expensive because you must now
perform the cast
(int)x explicitly. Well it was already done for you in the is examination.
So in this regard it is a bit wasteful since a cast is performed implicitly
and explicitly by the run-time and by your code. The as operator is provided
as a work-around for this inefficiency.

You are likely to incur extra expense if you wrap the is test in a function
simply because a function requires overhead and stack space.
 
But what if have a lot of options. Example:

class Base { ...}
class D1: Base {...}
.....
class D7: Base {...}

and the code somewhere:

if(x is D1) { do smth. }
.....
else if(x is D7) { do smth.}

Consider the case when there is no good way to pack these "do-smth"-code in
virtual methods.
Here I can test whether x has type Dx for a few time while I perform one
type-cast only.

And the question is whether the is-test is as fast as virtual function call.
If the is-test is slower than I can implement this scenario the following:

class B { public abstract virtual int d(); }
class D1: Base { public override int d() { return 1; }...}
....
class D7: Base { public override int d() { return 7; }...}

And the code:

int d = x.d();
if(d==1) { do smth. }
.....
else if(d==7) { do smth.}

I like the first variant more. But what about performance?
 
As I've already stated, a virtual call involves a necessary overhead hit
just because it is a function call. I do agree that it is probably cleaner
to use virtual methods in this case. If you are worried about performance,
it's not the way to go. Have a look at the as operator.

object d;
d as string;
if (d != null)
do something
d as int
if(d != null)
do something

I haven't measured it and that's the only way to know for sure but this way
should be faster than a function call.

regards
 
Back
Top