I have been trying to optimize the performance of access to a time-critical class. When I measured, I was surprised to find a significant difference in performance between Member access and Property access. See example below:
using System;
using System.Diagnostics;
public class ClassSample {
public static int StaticField = 0;
public int InstanceMember = 0;
public int PropertyField { get; set; }
public ClassSample() {
PropertyField = 0;
}
}
public class Program {
public static void Main(string[] arg) {
var obj = new ClassSample();
int N = 10000000;
Stopwatch sp = new Stopwatch();
sp.Start();
int total = 0;
for (int i = 0; i < N; i++) {
ClassSample.StaticField = i;
total += ClassSample.StaticField;
}
sp.Stop();
Console.Out.WriteLine("Static :\t" + sp.Elapsed);
sp.Restart();
total = 0;
for (int i = 0; i < N; i++) {
obj.InstanceMember = i;
total += obj.InstanceMember;
}
sp.Stop();
Console.Out.WriteLine("Member: \t" + sp.Elapsed);
sp.Restart();
total = 0;
for (int i = 0; i < N; i++) {
obj.PropertyField = i;
total += obj.PropertyField;
}
sp.Stop();
Console.Out.WriteLine("Property:\t" + sp.Elapsed);
}
}
Where I run this (.Net 4.5/Windows 10), I get these results:
Static : 00:00:00.0243832
Member: 00:00:00.0240386
Property: 00:00:00.0624915
So the Property access is more than twice slower than the others. Is this expected? Any way to avoid it?