.netperformancepropertiesbacking-field

Is there a performance difference between properties vs. backing fields in read/write operations?


When working within a class on its own fields and properties, I typically only use the property when it performs some function (like limiting a value or validating or whatever). Otherwise I prefer to read/write the backing field directly.

I somehow got it in my head that this would be a more generally performant way to do things, but it occurred to me that I don't really have any evidence to support this idea.

Aside from convention or taste, is there an actual performance factor between one and the other methods?


Solution

  • If the property is a straight get/set its compiled away - in other words, the compiler will turn either using the property or the field directly into the same thing - so no performance difference.

    However, get/sets can incorporate whatever logic they want so can be expensive - however, guidelines often advise keeping them light.

    Properties have a few benefits, even if they are just get/set covers:

    Just as an aside, although it is interesting to review the minute performance characteristics of these things - in production code applying this type of optimisation (well, in this case there isn't one) would likely come under the banner of premature optimisation.