Which of these pieces of code is faster?
if (obj is ClassA) {}
if (obj.GetType() == typeof(ClassA)) {}
Edit: I'm aware that they don't do the same thing.
Which of these pieces of code is faster?
if (obj is ClassA) {}
if (obj.GetType() == typeof(ClassA)) {}
Edit: I'm aware that they don't do the same thing.
This should answer that question, and then some.
The second for those that don't want to read the article.
Answered a similar question here: http://stackoverflow.com/questions/57701/what-are-the-performance-characteristics-of-is-reflection-in-c#57713
They don't do the same thing. The first one works if obj is of type ClassA or of some subclass of ClassA. The second one will only match objects of type ClassA. The second one will be faster since it doesn't have to check the class hierarchy.
For those who want to know the reason, but don't want to read the article referenced in http://stackoverflow.com/questions/184681/is-vs-typeof#184697.
Does it matter which is faster, if they don't do the same thing? Comparing the performance of statements with different meaning seems like a bad idea.
is
tells you if the object implements ClassA
anywhere in its type heirarchy. GetType()
tells you about the most-derived type.
Not the same thing.
wanna be really fast? if u have limited number of subtypes just create enum for identification.