Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 274
Dan Avatar asked May 24 '13 17:05

Dan


People also ask

What is the difference between GetType and typeof?

typeof keyword takes the Type itself as an argument and returns the underline Type of the argument whereas GetType() can only be invoked on the instance of the type.

How fast is GetType C#?

1500 milliseconds for the first approach and approx. 2200 milliseconds for the second. (code and timings corrected - doh!)

What is the use of typeof ()?

typeof is an operator to obtain a type known at compile-time (or at least a generic type parameter). The operand of typeof is always the name of a type or type parameter - never an expression with a value (e.g. a variable). See the C# language specification for more details.

What is GetType?

GetType Method is used to find the type of the current instance. This method returns the instances of the Type class that are used for consideration. Syntax: public Type GetType (); Return Value: This method return the exact runtime type of the current instance.


2 Answers

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().

like image 84
Marc Gravell Avatar answered Oct 23 '22 03:10

Marc Gravell


I would go with type2. It doesn't require instantiating an instance to get the type. And it's the most human readable.

like image 43
mason Avatar answered Oct 23 '22 03:10

mason