Performance of Object.GetType()

前端 未结 7 1818
花落未央
花落未央 2020-12-05 03:44

We have lots of logging calls in our app. Our logger takes a System.Type parameter so it can show which component created the call. Sometimes, when we can be bothered, we

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-05 04:17

    The GetType() function is marked with the special attribute [MethodImpl(MethodImplOptions.InternalCall)]. This means its method body doesn't contain IL but instead is a hook into the internals of the .NET CLR. In this case, it looks at the binary structure of the object's metadata and constructs a System.Type object around it.

    EDIT: I guess I was wrong about something ...

    I said that: "because GetType() requires a new Object to be build" but it seems this is not correct. Somehow, the CLR caches the Type and always returns the same object so it doesn't need to build a new Type object.

    I'm based on the following test:

    Object o1 = new Object();
    Type t1 = o1.GetType();
    Type t2 = o1.GetType();
    if (object.ReferenceEquals(t1,t2))
        Console.WriteLine("same reference");
    

    So, I don't expect much gain in your implementation.

提交回复
热议问题