Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typeof(T) vs. Object.GetType() performance

Tags:

People also ask

What is the difference between typeof and GetType?

The typeof operator takes a type as a parameter. It is resolved at compile time. The GetType method is invoked on an object and is resolved at run time. The first is used when you need to use a known Type, the second is to get the type of an object when you don't know what it is.

How fast is GetType C#?

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

Is typeof compile time?

The typeof is an operator keyword which is used to get a type at the compile-time. Or in other words, this operator is used to get the System.

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.


Is anyone aware of any differences between typeof(T) where T : struct, for example, vs. t.GetType() where t is a System.Object?
ILdasm shows that typeof(T) uses System.Type::GetTypeFromHandle(RuntimeTypeHandle handle), and the other is just plain System.Object::GetType(). The implementations are [MethodImpl(MethodImplOptions.InternalCall)], so the methods are defined in native code in the CLR. So, I'm just wondering if anyone is aware of any reason to prefer one over the other?

EDIT: Let me clarify, I'm mostly interested in the cases where it doesn't seem to matter which you choose - that is, is there a performance difference, or any other reason? Thanks!