事实到底是什么-字段与属性-性能差异? [英] Nothing but the truth - fields vs. properties - performance differences?

查看:119
本文介绍了事实到底是什么-字段与属性-性能差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就在几分钟前,我读了-一本经常听到的-在一本c#书籍中有关属性及其私有字段的用法的提示,其中指出避免直接设置或获取私有字段.因此,众所周知,通常访问属性进行错误检查更为有用,并且可以在一个位置(该属性)进行更改.如果这是唯一的事实,那么在延迟启动的情况下,可以并且因此应该避免使用字段,对吗?
但是,据我所知,字段的执行速度比c#中的属性要快得多(尤其是循环中).我认为在codeproject上有关于此主题的文章(找不到它找到了它 C#中的快速循环和不太快速循环 [ ^ ]).至少对于性能优化字段应尽可能使用,对吗?
那么您有什么意见/最佳做法?

Just a few minutes ago i read - a quite often heard - hint in a c# book about the usage of properties and their private fields, where it says to avoid setting or getting private fields directly. So as we all know, in general it is more useful to access a property for error checking and changes may be done at one place, the property. If this is the only truth, in case of a lazy initiation, fields could, and therefore should be avoided generally, right?
But, as far as I know fields perform much faster than properties in c# (esp. in loops). I think there is an article about this topic here on codeproject (could not find it found it Fast and Less Fast Loops in C#[^]). At least for performance optimization fields should be used whenever possible, correct?
So what’s your opinion/ best practices?

推荐答案

否.属性和田野是完全不同的动物.

字段用于内部类的存储-如果使外部环境可以访问它们,则您正在修复类的设计,因为如果不考虑对外部世界的影响,就无法更改类的工作方式.从可靠性/维护的角度来看,这是一个非常糟糕的主意.

属性实际上是超级字段:可以将其设置为公开可用以供读取,以及可以私有方式供其编写(反之亦然),这进一步限制了外界可以对您的类数据执行的操作.它们还可以用作返回未单独保存的已处理信息的字段.

它们可能比类似的领域高效得多.例如,考虑一个容纳学生的班级.您可以检索到的有关学生的一项内容是高分辨率的图片:2048 x 2048,全彩色.如果使用图像"字段,则在创建Student实例时始终必须检索图像,并从数据库中获取所有记录信息.

如果通常在没有图像的表中显示这些内容,那么这将浪费大量时间,内存和数据库带宽.如果使用属性,则只有在要求输入图像时,才能检索图像:
No. Properties and fields are very different animals.

Fields are used for internal class storage - if you make them accessible to the outside world, then you are fixing the design of your class, because you cannot change how your class works without considering the effects on the outside world. From a reliability / maintenance point of view this is a very bad idea.

Properties are in effect super-fields: they can be made publicly available to read, and privately to write (or vice versa), which further restricts what the outside world can do with your class data. They can also act as a field returning processed information which is not held separately.

They can be much, much more efficient than a similar field. For example, consider a class holding Students. One of the items you can retrieve about the student is a picture of them, in high resolution: 2048 by 2048, full colour. If you use an Image field, then you always have to retrieve the image when you create the Student instance, getting all record info from the database.

If you normally display these in a table, without the image, then that is incredibly wastefull of time, memory and database bandwidth. If you use a property, then you can retrieve the image only when it is asked for:
private Image studentPhoto = null;
public Image StudentPhoto
   {
   get 
      {
      if (studentPhoto == null)
         {
         studentPhoto = GetImage();
         }
      return studentPhoto;
      }
   }


有趣.尽管我从未听说过会导致性能问题的属性(无论如何,如果没有进一步的逻辑,就不会是属性),但我猜可能会有一些开销. .NET中的Property只不过是get和set方法的包装.这意味着在IL中,属性就像其他方法一样简单.
当然,您可以在属性"中放入很多代码(尽管通常不建议这样做),这可能会导致性能问题.
我个人尝试尽可能多地调用我的属性,因为它们可以获取一些验证逻辑或调用OnPropertyChanged.我只是想确保自己从该代码中受益,而不必遍历类将对字段的所有调用都更改为对Property的调用(除非出于某种原因我想解决这个问题).
最重要的是,性能影响很小,您甚至不必考虑它. 几毫秒可进行10000000次读/写 [有关此问题的更多信息 [ ^ ].
自我实现的属性与公共字段 [
Interesting. Though I never heard of Properties causing performance issues (not Properties without further logic anyway) I guess there could be slight overhead. A Property in .NET is nothing more than a wrapper for a get and set Method. That means that in IL Properties are simply Methods like any other.
Of course you could put a lot of code in Properties (although this is usually not recommended) which could cause performance issues.
Personally I try to call my Properties as much as possible, since they could get some validation logic or call OnPropertyChanged. I just want to make sure I benefit from that code without having to go through my Class to change all the calls to my field into a call to my Property (unless I want to get around this for some reason).
On top of that the performance hit is so very minor that you should not even have to think about it. A few milliseconds for 10000000 read/writes[^]. Optimizing that would be pretty futile :)
Some more on this issue[^].
Self-Implemented Properties versus Public Fields[^] Is that the CP article you referred to?

By the way, speaking from experience, putting to much logic in Properties is a bad idea. I had a Property that made some calls to the database (actually I did a LINQ query on an ObjectContext). When binding to those Properties each value I altered caused my program to hang for about two seconds... Now THAT needed optimization, but not necessarily because they were Properties ;)


See Bills comment below. He is completely right and corrects me on an incompleteness in my answer :)


如果您想了解这实际上是如何实现的,网络上有几个信息源可以提供宝贵的见解:
致力于通用语言运行时(CLR)的代码生成功能团队的博客. [ ^ ]-这些是使得可以为在Microsoft .NET Framework之上运行的所有二进制文件生成本机代码.

.NET Framework 3.5 SP1中的CLR优化 [
If you want to understand how this actually works out there is a couple of information sources on the net that provides valuable insights:
The blog for the code generation feature team working on the Common Language Runtime (CLR). [^] - these are the guys that that make it possible to generate native code for all binaries that run on top of the Microsoft .NET Framework.

CLR Optimizations In .NET Framework 3.5 SP1[^].

Simple properties will usually be inlined by the optimizer, so in the end there is no performance hit.

Best regards
Espen Harlinn


这篇关于事实到底是什么-字段与属性-性能差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆