Apr 30, 2009

Reflection performance

int x = 10;
Assembly a = Assembly.Load("mscorlib");

Type t1 = typeof(int);
Type t2 = x.GetType();
Type t3 = a.GetType("System.Int32");
Type t4 = Type.GetType("System.Int32");

Console.WriteLine(t1 == t2);
Console.WriteLine(t2 == t3);

Console.WriteLine(t3 == t4);

All of the equality comparisons will evaluate to true and, assuming that Type's Equals method is transitive (as all Equals implementations are supposed to be), then we can infer that t1 == t2 == t3 == t4. Loading t1 is the most efficient, t2 is a close second, and t3 and t4 are horribly inefficient. t3 is slightly more efficient because it only searches mscorlib.dll, whereas t4 searches all loaded assemblies. In fact, in a little test program I wrote, t2 is twice as slow as t1, t3 is 100 times slower than t2, and t4 is twice as slow as t3.