Friday, February 15, 2008

Field or Property?

A coworker asked me a simple question that I really just didn't know. What is faster, a field or a property? I know a property has the get and set, but I thought since the property was pointing to a field that it would be equally comparable. So being geeks we put the question to the test. Created a simple console application with a field "A" and a property "B" and bench marked 100 repetitions.

static string A = "";

static string _B = "";
property static string B
get {return _B;}
set {_B = value;}

Then within the main method we create a StopWatch from System.Diagnostics and ran the following loops:

StopWatch stopWatch = new StopWatch();

for(int j=0; j<100; j++) A=A;
Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "Field A took {0} mil.", stopWatch.ElapsedTime.TotalMilliseconds);

for (int i=0; i<100; i++) B=B;
Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "Property B took {0} mil.", stopWatch.ElapsedTime.TotalMilliseconds);

Field A took 0.0025 mil.
Property B took 0.4457 mil.

The biggest shocker to me was that a field is 99% faster than the property. Now I know there is the getter and setter but I had no idea it had that much of an impact over a field. I hope that after someone reads this their not going to go out and change their code from using properties to using fields. The point of this entry was not to remove properties but to understand the question at hand. Remember private fields do not serialize to xml if your class is marked as serializable so don't run out and change anything. A few milliseconds difference is not enough to make me go out and change an application unless its an intense gaming app in which case we want the fastest processing possible. Properties are awesome and we all should be using them. This test was a great experiment in knowing that if a property is only being used to store a value and your class is not serializable then it doesn't hurt to use a field instead of the property for a very small unrecognized performance gain. But all in all I still love properties and intend to continue using them.

1 comment:

Anonymous said...

Different benchmark results here:

Creative Commons License
Blogged Information and Code is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License.