Performance overhead for properties in .NET

前端 未结 9 1886
隐瞒了意图╮
隐瞒了意图╮ 2020-12-10 01:43

I read somewhere that having public properties is preferable to having public members in a class.

  1. Is this only because of abstaraction and modularity? Are

相关标签:
9条回答
  • 2020-12-10 02:15

    If you want a specific example of something that properties are needed for that you can't do with regular member variables, think about inheritance: if a class uses a public member, derivations to this class cannot implement validation or other getter/setter behavior. They're stuck with the variable as it is, and if they want to do something different, they have to 1) ignore the existing member variable and create a new property, 2) add a new property, and 3) override every method that called or relied on the member variable to use the property instead. Not only is this unnecessarily more work, if the person writing the derived class doesn't have access to the source it may be nearly impossible.

    If the base class uses properties instead of member variables, it's just a question of adding the validation or other behavior to the get/set function, and you're done.

    0 讨论(0)
  • 2020-12-10 02:18

    I've asked the same question before.

    I'm guessing you're using VS2008, are using a 64-bit OS and have compilation set to "Any CPU"? If so, properties don't get inlined by the x64 JIT compiler. They do on 32-bit, making them identical in performance to public fields.

    0 讨论(0)
  • 2020-12-10 02:21

    It is mostly for purposes of abstraction (you can later add validation without breaking existing code, or requiring recompilation).

    Even when using auto-properties, there is still a backing field generated by the compiler, and will perform as such.

    0 讨论(0)
提交回复
热议问题