Efficiency of C#'s typeof operator (or whatever its representation is in MSIL)

Viewed 5151

I know premature optimization is the mother of all evil. However, I am defining a generic method that uses Reflection to retrieve its generic type's metadata, and would like to know whether calling typeof(T) several times as in the following code snippet:

private static Dictionary<Type, PropertyInfo[]> elementProperties;

private static T MakeElement<T>(SqlDataReader reader) where T : class, new() {
    PropertyInfo[] properties;
    if (elementProperties.ContainsKey(typeof(T)))
        properties = elementProperties[typeof(T)];
    else
        properties = elementProperties[typeof(T)] = typeof(T).GetProperties();

    // more code...
}

... is less efficient than storing the type object into a variable as in the following code snippet:

private static Dictionary<Type, PropertyInfo[]> elementProperties;

private static T MakeElement<T>(SqlDataReader reader) where T : class, new() {
    PropertyInfo[] properties;
    Type type = typeof(T);
    if (elementProperties.ContainsKey(type))
        properties = elementProperties[type];
    else
        properties = elementProperties[type] = type.GetProperties();

    // more code...
}

...?

If I understand compiler theory correctly (and I think I do), this question could be reduced to the following one:

When the JIT compiler instantiates a generic type, does it replace every instance of [whatever the MSIL representation of typeof(T) is] with...

  1. ... a reference to the actual type object? (good)
  2. ... a method call/subroutine/whatever that retrieves a reference to the actual type object? (bad)
  3. ... a method call/subroutine/whatever that constructs a type object and returns a reference to it? (very, very bad)
3 Answers
Related