471,305 Members | 1,520 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,305 software developers and data experts.

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

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(B aseType)))
{
}

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.

Feb 6 '06 #1
1 3438
whoops, that should be: http://markrdawson.blogspot.com/

time for sleep :-)

"Mark R. Dawson" wrote:
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(B aseType)))
{
}

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.

Feb 6 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

40 posts views Thread by Steve Juranich | last post: by
9 posts views Thread by Fresh Air Rider | last post: by
28 posts views Thread by Act | last post: by
24 posts views Thread by hjbortol | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.