This question has been around in my mind for a while so I decide to give it a test.
The test is simple, directly set property value, verse using PropertyInfo to set the value. To make things more interesting, I also tested set value in Dictionary.
The result: 232 times (27166 / 117) slower!
In 1 million test runs,
- direct access value: 117 milliseconds
- PropertyInfo: 27166 milliseconds
- Dictionary: 266 milliseconds
class Employee
{
private string _firstName;
private string _lastName;
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
[TestMethod]
public void PropertyPerformanceTest()
{
int maxLoop = 1000000;
long durationDirect = 0;
long durationProperty = 0;
long durationDictionary = 0;
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < e =" new" firstname = "Joan" lastname = "Smith" durationdirect =" sw.ElapsedMilliseconds;" pilastname =" typeof(Employee).GetProperty(" pifirstname =" typeof(Employee).GetProperty(" i =" 0;" e =" new" durationproperty =" sw.ElapsedMilliseconds;"> employeeValue = new Dictionary
employeeValue.Add("LastName", null);
employeeValue.Add("FirstName", null);
sw.Start();
for (int i = 0; i < e =" new" durationdictionary =" sw.ElapsedMilliseconds;"> durationDictionary);
Assert.IsTrue(durationDictionary > durationDirect);
}