.Net 4.0 Reflection vs. Dynamics vs. Property Setting With Times
Hello All,
Today I found my self hanging out after a sprint review with my partner in crime Kevin Rohling. TFS was down (not tfs's fault, but some other freak accident...) and I hadn't installed VS 2010 yet, so it seemed like the perfect time to do such things. I got everything up and running, and Kevin and I got into a discussion about Dynamics & performance. We made a quick lunch bet on which is faster, reflection or dynamics for simply setting a property. I figured reflection would be quicker, while Kevin thought dynamics would be faster. Well, I owe him lunch now. The code is below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var nTimes = 1000000;
var value = "Hello World";
var myTestType = new MyTestType();
DateTime start, end;
var property = typeof(MyTestType).GetProperty("MyDynamicProperty");
start = DateTime.Now;
for (var i = 0; i < nTimes; i++)
{
//var property = typeof(MyTestType).GetProperty("MyDynamicProperty");
property.SetValue(myTestType, value, null);
}
end = DateTime.Now;
Console.WriteLine(end.Subtract(start).ToString());
dynamic myTestType2 = new MyTestType();
start = DateTime.Now;
for (int i = 0; i < nTimes; i++)
{
myTestType2.MyDynamicProperty = value;
}
end = DateTime.Now;
Console.WriteLine(end.Subtract(start).ToString());
var myTestType3 = new MyTestType();
start = DateTime.Now;
for (int i = 0; i < nTimes; i++)
{
myTestType3.MyDynamicProperty = value;
}
end = DateTime.Now;
Console.WriteLine(end.Subtract(start).ToString());
Console.ReadLine();
}
public class MyTestType
{
public string MyDynamicProperty { get; set; }
}
}
}
Results:
Reflection: 00:00:19.8581040
Dynamics: 00:00:00.6054300
Setting a property plain and simple: 00:00:00.0166005
Kevin was right by a long shot!! Who would have guessed that dynamics would be so fast. I'm quite impressed, and tip my hat to the guys that cooked that up! Cheers fellas, but thanks a lot for making my buy lunch...
On a side note: Congrats to Kevin Rohling on his winning new CloudApp() with his submission of www.myimpulselive.com! Check out the app. It's pretty darn slick!