C# 中的自动属性不会造成开销吗?
当我有自动属性并且我尝试从它的类中访问它时,这似乎是一种开销,因为我使用一个函数来访问我的类的成员,而不是直接访问它。
如果这是正确的,也许我应该考虑在这种情况下不使用自动属性?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您是否测量过任何理论开销并发现它很重要?这是做出基于绩效的决策的关键。
在这种情况下,我完全希望 JIT 能够内联自动实现的属性,从而消除任何性能开销。 (我似乎记得看到过一个带有
float
/double
的案例,但事实并非如此,但那是不久前的事了 - 甚至那么开销就很小了。)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.)在这方面,自动属性与普通属性没有什么不同。
不用担心;无论如何,JITter 通常都会内联属性方法。
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.
你是对的。但是,某些机制需要属性,例如 XML 序列化程序不会序列化公共成员...
另一件事是封装 - 您永远不会提前知道类的每个属性的最终目的地是什么,因此如果您将其创建为属性首先,您可以稍后再进入 set/get 实现。
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.
如果您遵循面向对象原则,则允许直接访问内部成员将违反封装原则。属性机制(getter 和 setter 方法)提供对这些成员的正确访问,保护内部成员免遭直接访问。
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.