Field Access Performance Tests
Dave Peck has a post about the performance of Linq over collections, where he makes the comment:
I never even heard on this issue, so I decided to make a check, here is my test harness:
static void Main(string args)
Normal current = new Normal();
DateTime start = DateTime.Now;
for (int i = 0; i < 1000000; i++)
temp = Normal.Static + i;
TimeSpan span = DateTime.Now - start;
Laughably simple, but it should give a fair idea about the issues. BTW, I'm using the string concatation as a way to prevent the compiler from optimizing the access. I would guess that this affect negatively on the result, but I'm not concerned about accuracy, I want to know the general amount of difference.
Here are the classes that I tested:
public class Normal
public static string Static = "static-string";
public string Instance = "instance-string";
public class Generic<T>
public static T Static;
public T Instance;
public class Generic2<T>
public static string Static = "generic2-static-string";
public string Instance = "generic2-instance-string";
public T something;
The results are below. I would just like to note that this represent a couple of runs only, and I have seen the numbers jump around in about 100-50 ms difference.
- Normal Static: 625ms.
- Normal Instance: 609ms.
- Generic Static: 578ms.
- Generic Instance: 609ms.
- Generic2 Static: 593ms.
- Generic2 Instance: 578ms.
Base on this inclunclosive result, I don't think that there is any significant difference with regard to performance in access static or instnace field on generic class (or normal ones). In the tests above, all the results were fairly consistenly in the same range.