1
class TestClass
{
    public void Test()
    {
        //which is faster?
        object o1 = MethodRequiringType(typeof(TestClass));
        object o2 = MethodRequiringType(this.GetType());
        //which is better?
        //does it matter?
    }

    public object MethodRequiringType(Type t)
    {
        return new { }; 
    }
}
Seattle Leonard
  • 6,548
  • 3
  • 27
  • 37
  • and now that I'm searching... http://stackoverflow.com/questions/983030/type-checking-typeof-gettype-or-is http://stackoverflow.com/questions/139607/what-is-the-difference-between-mycustomer-gettype-and-typeofcustomer-in-c – froadie Jul 09 '10 at 19:08
  • Your two statements are not always equivalent. So the answer to the questions for which one is "better" or whether it "matters" is: it depends. – Esteban Araya Jul 09 '10 at 19:11
  • @Esteban - You're absolutely right. I suppose the better question is "when should you use which?". – Seattle Leonard Jul 09 '10 at 19:38

3 Answers3

3

Worry about correctness before performance. If there are any classes derived from TestClass, you won't get the same result.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
3

A quick google search revealed this:

GetType is a call that is made at runtime on an instance of an object. typeof() is resolved to a call at runtime, but loads the type from the token for the type. They probably resolve to the same call, it's just that GetType requires an instance. If I didn't need the instance, I would use typeof.

and also:

Also be aware that GetType is virtual, and gives you the type of the object, not the declared type of the reference. That is:

Object o = new String();

typeof(o) Object type

o.GetType() String type

Swift
  • 13,118
  • 5
  • 56
  • 80
2

I've actually measured this difference for a lecture I once gave (on reflection and optimization).

Bottom line: if you plan on calling that line several billion times, you'll save a second using the typeOf() instead of the GetType()

SWeko
  • 30,434
  • 10
  • 71
  • 106
  • I read somewhere (http://msdn.microsoft.com/en-us/magazine/cc163759.aspx) with regard to Reflection that the call to GetType was specifically optimized in the JIT compiler, since it is such a commonly used method, as opposed to other Reflection operations such as finding the MemberInfo for a specific member of a type. – Dr. Wily's Apprentice Jul 09 '10 at 19:57
  • `GetType` is optimized. That still doesn't make it as fast as `typeof`. – Ben Voigt Jul 10 '10 at 06:59
  • @Ben, I definitely agree. I didn't mean to sound like I was suggesting to use GetType over typeof in general, so thanks for catching me on that. The article actually mentions that the typeof operation is optimized as well. – Dr. Wily's Apprentice Jul 10 '10 at 20:14
  • What I'm saying is that the difference is not at all important. There are lots of performance bottlenecks with more impact, than saving a few nanoseconds on a GetType/typeof – SWeko Jul 10 '10 at 20:32