I have a program that requires fast performance. Within one of its inner loops, I need to test the type of an object to see whether it inherits from a certain interface.
One way to do this would be with the CLR's built-in type-checking functionality. The most elegant method there probably being the 'is' keyword:
if (obj is ISpecialType)
Another approach would be to give the base class my own virtual GetType() function which returns a pre-defined enum value (in my case, actually, i only need a bool). That method would be fast, but less elegant.
I have heard that there is an IL instruction specifically for the 'is' keyword, but that doesn't mean it executes fast when translated into native assembly. Can anyone share some insight into the performance of 'is' versus the other method?
UPDATE: Thanks for all the informed answers! It seem a couple helpful points are spread out among the answers: Andrew's point about 'is' automatically performing a cast is essential, but the performance data gathered by Binary Worrier and Ian is also extremely useful. It would be great if one of the answers were edited to include all of this information.
Using is
can hurt performance if, once you check the type, you cast to that type. is
actually casts the object to the type you are checking so any subsequent casting is redundant.
If you are going to cast anyway, here is a better approach:
ISpecialType t = obj as ISpecialType;
if (t != null)
{
// use t here
}