gpt4 book ai didi

c# - 为什么 Property 执行比 Field 或 Method 执行慢?

转载 作者:可可西里 更新时间:2023-11-01 09:01:20 24 4
gpt4 key购买 nike

CLR via CSharp第 10 章“属性”Jeff Richter 写道:

A property method can take a long time to execute; field access always completes immediately. A common reason to use properties is to perform thread synchroni- zation, which can stop the thread forever, and therefore, a property should not be used if thread synchronization is required. In that situation, a method is preferred. Also, if your class can be accessed remotely (for example, your class is derived from System.MarshalByRefObject), calling the property method will be very slow, and therefore, a method is preferred to a property. In my opinion, classes derived from MarshalByRefObject should never use properties.

即使属性被定义为只返回私有(private)字段,情况也是如此吗?为什么在同步中首选方法?为什么在 MarshalByRefObject 场景中首选方法

为了澄清我的问题:
Jeff 似乎在笼统地声明属性不可取,而在这两种情况下方法更可取。正如 Joe White 指出的那样,属性可以有任意代码。但是方法可以运行相同的任意代码。那是我遇到困难的部分。使用方法而不是属性(假设使用相同的代码)进行同步或编码实际上有优势,还是他只是在语言约定方面有问题?

最佳答案

我认为他的意思是,因为一个属性可以运行任意代码,调用代码不应该假设它会立即完成。

如果属性所做的只是返回一个字段,那么它的方法体实际上将由 JIT 编译器内联,并且它的速度将与字段访问一样快。所以并不是说属性在某种程度上变慢了;那是因为它们是黑盒子。如果您不知道某个属性是如何实现的,就无法对其快速返回做出假设。

(也就是说,制作一个慢速属性将明显违反 .NET Framework Design Guidelines ,特别是这个:“请使用方法,而不是属性,[如果]操作比字段慢几个数量级设置为。)

至于他建议改用方法,我无法理解。属性方法:属性getter是一个方法(通常命名为get_PropertyName),属性setter是一个方法(set_PropertyName),代码读取属性的代码被编译为对 get_PropertyName 进行方法调用的代码。没有什么特别之处会使属性比方法慢。

关于c# - 为什么 Property 执行比 Field 或 Method 执行慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9161311/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com