tags:

views:

920

answers:

5
+1  Q: 

is vs typeof

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.

+10  A: 

This should answer that question, and then some.

The second for those that don't want to read the article.

MagicKat
+1: In the past I wondered why the C# compiler didn't compile `typeof(string).TypeHandle` to the `ldtoken` CIL instruction, but it looks like the CLR takes care of it in the JIT. It still takes a few extra opcodes but it's a more generalized application of the optimization.
280Z28
+1  A: 

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.

tvanfosson
+10  A: 

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.

Jay Bazuzi
It does matter, because in my case I'm positive they return the same result.
ilitirit
@[ilitirit]: they return the same result right now, but if you add a subclass later they won't
Steven A. Lowe
Optimising now will make your code brittle and difficult to maintain.
ICR
My classes are sealed.
ilitirit
+1 for the correct answer
Allen
A: 

wanna be really fast? if u have limited number of subtypes just create enum for identification.

alexm