Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?


1 Answers

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:

  • Data binding can only see properties, not fields.
  • It keeps with the concept of encapsulation.
  • You can enforce read only or write only semantics.
  • You can apply attributes separately to the underlying field (useful in serialisation scenarios).

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.

like image 83
Adam Houldsworth Avatar answered Jul 02 '26 03:07

Adam Houldsworth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!