简体   繁体   中英

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

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!

typeof is used when you want to get the Type instance representing a specific type. GetType gives the runtime type of the object on which it is called, which may be different from the declared type.

For example:

class A {}

class B : A {}

class Program
{
    static A CreateA()
    {
        return new B();
    }
 
    static void Main()
    { 
        A a = CreateA();
        Console.WriteLine(typeof(A));     // Writes "A"
        Console.WriteLine(a.GetType());   // Writes "B"
    }
}

In the above case, within the Main method, you're dealing with instances of type A ; thus, if you care about the declared type, you would use typeof(A) . However, the CreateA method actually returns an instance of a derived class, B , despite declaring the base class as the return type. If you want to find out about this runtime type, call GetType on the returned instance.

Edit : Mehrdad's comment points in the right direction. Although typeof emits a GetTypeFromHandle call that takes a RuntimeTypeHandle as parameter, the said parameter would actually correspond to the specific type whose metadata token is on the evaluation stack. In some instances, this token would be there implicitly (due to the current method invocation); otherwise, it can be pushed there explicitly by calling ldtoken . You can see more examples of this in these answers:

Edit 2 : If you're looking for performance benchmarks, you can refer to Jon Skeet's answer . His results were (for 100 million iterations):

typeof(Test):   2756ms
test.GetType(): 3734ms

Well, sometimes in generic code, you know the compile time type from a type parameter T , without having an instance. Then you must use typeof(T) .

At other times, typically in non generic code, you might be interested in the runtime type of an object. Then you use GetType() .

So in some cases, depending on what you want to know, or what you can query for, you only have one option.

And sometimes, you could choose.

You use typeof when you want compile-time information and GetType when you want runtime information.

If you're in a situation where you can use either, you should use typeof because it can be resolved at compile-time. This makes it clearer what the Type value will be and (in principle) allows more optimizations.

The typeof keyword takes a compile-time type identifier and gives you the corresponding runtime instance of Type:

Type intType = typeof(int);
Type stringType = typeof(string);
Type objectType = typeof(object);
Type genericType = typeof(T);

// not permitted: typeof(1), typeof(someVariable)

The GetType instance method takes a run-time instance and tells you its exact runtime type:

Type intType = 1.GetType(); // typeof(int)
Type objectType = new Object().GetType(); // typeof(object)

object x = "test";
Type stringType = x.GetType(); // typeof(string), NOT typeof(object)

// not permitted: int.GetType(), string.GetType(), T.getType()

You typically only need to use typeof or GetType when writing something that does reflection, creating expression trees by hand, or using the terrible Enum methods (which take an instance of Type instead of a generic type parameter).

GetType()用于检索您实际拥有的实例类型,但typeof()用于获取您没有的实例类型, GetType()在运行时解析,而typeof()在编译时解析。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM