When is it okay to use fields? When are properties yagni? This was the topic of an email thread I was recently involved in. A friend of mine had determined to answer - once and for all - the overhead of using properties. The results of his testing indicated that property-usage has negligible impact on execution time. That in all but the most dire situations, property-usage is not a performance variable.
I actually looked into this about two years ago. I wrote a console app that benchmarked field/property access and mutation. The results were similar. But what I found useful was to compare the MSIL operations. The attached source is similar to that original code. It was compiled, tested, and disassembled under mono on Linux. You can run the binary as console app or nunit test fixture.
Take a look at BenchmarkTest.exe.ildasm - specifically line 0x15 in FieldAccessTest:
IL_0015: ldfld int32 appl...BenchmarkTest::'field'
and PropertyAccessTest:
IL_0015: call instance int32 class appl...BenchmarkTest::get_Property()
As you can see property access has the overhead of a call stack - nothing more, nothing less. In reality this amounts to a few milliseconds difference (try it yourself). This brings us back to the original question: when to NOT use properties. The answer is never. The overwhelming advantages of abstraction and derived behavior far outweighs the puny difference in execution time.
As my brother put it,
When the performance gain is so small it's best to follow good programming practices. Using fields to gain such a small performance gain can cause all kinds of issues just because you wanted to save a few CPU cycles that will never be missed.
| Attachment | Size |
|---|---|
| property-field-benchmarks.tar.gz | 113.05 KB |