Inheritance Resolving, IsSubclassOf vs "is" vs "as" performance

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

A while ago there was a post where someone asked how to find if a type was
derived from another type, three ways were mentioned:

Solution1:
if(derivedInstance.GetType().IsSubclassOf(typeof(BaseType)))
{
}

Solution2:
if(derivedType is BaseType)
{
}

Solution3:
BaseType temp = derivedType as BaseType;
if(temp != null)
{
}

The relative performance of these three methods was also brought up, with
the is and as operator being mentioned as the faster way, I was curious to
see the difference in speed so I ran a little test, for the worst case, 9
levels of inheritance and 1,000,000 iterations:

solution1 -> took 949ms for 1,000,000 iterations
solution2 -> took 3ms for 1,000,000 iterations
solution3 -> took 2ms for 1,000,000 iterations

quite a difference if you are iterating many times. Just thought I would
share this with everyone. I put a more detailed list of results, along with
the code I ran at http://markdawson.blogspot.com

Maybe some of you will find this interesting.
Mark.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top