2

When I have automatic propertie and I try to access it from within it's class, it seems like an overhead, because I use a function to access a member of my class instead of just accessing it directlly.

If this is correct, maybe I should consider not to use automatic properties in such cases?

geniaz1
  • 1,143
  • 1
  • 11
  • 16
  • How is it an overhead? Have you measured it? An automatically implemented property is re-written at compile time so the execution time should be exactly the same as a manually implemented property. – Greg B Dec 20 '11 at 16:08
  • I'm not sure if its about automatic properties, but I did have a substantial speed boost once I made my automatic properties to member fields – nawfal Dec 04 '12 at 19:24

4 Answers4

5

Have you measured any theoretical overhead and found it to be significant? That's the key to making performance-based decisions.

In this case, I'd thoroughly expect the JIT to inline automatically-implemented properties, removing any performance overhead. (I seem to remember seeing a case with float / double where this wasn't the case, but that was a while ago - and even then the overhead was pretty small.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    I just tested it, with `float`/`double` they were inlined as well. Both setter and getter, both in 32bit mode and 64bit mode. (CLR 4.0) – harold Dec 20 '11 at 16:21
  • @harold: Goodo - I suspect this *may* have been CLR v2. It surprised me at the time :) – Jon Skeet Dec 20 '11 at 16:53
3

Automatic properties are no different from ordinary properties in this regard.

Don't worry about it; the JITter will typically inline the property methods anyway.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2

You are right on that. However, some mechanisms need properties, for example XML serializer won't serialize public members...

Other thing is encapsulation - you never know in advance what is the final destination of each property of your class, so if you create it as property at first, you can go into set/get implementation later.

Daniel Mošmondor
  • 19,718
  • 12
  • 58
  • 99
0

If you are following Object Oriented Principles, you would violate the Principle of Encapsulation by allowing access to your internal members directly. The Property mechanism (getters and setters methods) provide the proper access to these members protecting the internal members from direct access.

Bueller
  • 2,336
  • 17
  • 11