How Expensive Is Reflection?

I've seen many blog posts recently that give guidance on late binding with reflection versus early binding with casting.  What seems to always be missing is any data supporting the claims.  How can you tell me something is better without showing me how you know this? Here's my sooper scientific(read, not scientific) performance test to help demonstrate how much faster early binding can be over late binding using reflection. I ran each routine through 100 iterations, 1000, 10000, and 100000 iterations.

Late Bound Test Code

OK. The main point I wanted to test was the cost of getting a value from a property on an instance of "something" through reflection. This means calling type.GetProperty("SomeProperty").GetValue(instance, null). So here's the late bound code:


", type.GetProperty("ID").GetValue(item, null).ToString());
			html.AppendFormat("", type.GetProperty("Date").GetValue(item, null).ToString());
			html.AppendFormat("", type.GetProperty("Amount").GetValue(item, null).ToString());
			html.AppendFormat("", type.GetProperty("SalesRepName").GetValue(item, null).ToString());
		}
	}
}
private void LateBinding(IList orders, int iterations)
{
	for (int i = 0; i foreach (object item in orders)
		{
			Type type = orders[0].GetType();
			StringBuilder html = new StringBuilder();
			html.AppendFormat("
{0}{0}{0}{0}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

Early Bound Test

Basically this is using a generic List of type Order and the properties are accessed right off of each instance.


", item.ID);
			html.AppendFormat("", item.Date);
			html.AppendFormat("", item.Amount);
			html.AppendFormat("", item.SalesRepName);
		}
	}
}
private void EarlyBinding(List orders, int iterations)
{
	for (int i = 0; i foreach (Order item in orders)
		{
			StringBuilder html = new StringBuilder();
			html.AppendFormat("
{0}{0}{0}{0}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

Results or Whatever

There's actually quite a big difference, bigger than I thought before the sooper scientific test. Under 1000 iterations it's hard visibly see a difference, but over the 10,000 mark there is a major difference.

Here's my wicked cool test code in all it's glory.

 
Author: , 0000-00-00