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?
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.
1500 milliseconds for the first approach and approx. 2200 milliseconds for the second. (code and timings corrected - doh!)
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.
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.
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()
.
I would go with type2. It doesn't require instantiating an instance to get the type. And it's the most human readable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With