Search code examples
c#.netruntime-type

Which is more efficient: myType.GetType() or typeof(MyType)?


Supposing I have a class MyType:

sealed class MyType
{
    static Type typeReference = typeof(MyType);
    //...
}

Given the following code:

var instance = new MyType();
var type1 = instance.GetType();
var type2 = typeof(MyType);
var type3 = typeReference;

Which of these variable assignments would be the most efficient?

Is performance of GetType() or typeof() concerning enough that it would be beneficial to save off the type in a static field?


Solution

  • typeof(SomeType) is a simple metadata token lookup

    GetType() is a virtual call; on the plus side you'll get the derived type if it is a subclass, but on the minus side you'll get the derived class if it is a subclass. If you see what I mean. Additionally, GetType() requires boxing for structs, and doesn't work well for nullable structs.

    If you know the type at compiletime, use typeof().