Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

c# - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

Edit2: 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...