简体   繁体   English

C#深入访问对象性能

[英]C# deep accessing objects performance

I just want to know which of the following approach is recommended in terms of the performance and best practices. 我只是想知道在性能和最佳实践方面推荐以下哪种方法。 Is there any performance difference? 有任何性能差异吗?

if (objA.objB.objC.objD.objE != null)
{
   objX.var1 = objA.objB.objC.objD.objE.prop1;
   objX.var2 = objA.objB.objC.objD.objE.prop2;
   objX.var3 = objA.objB.objC.objD.objE.prop3 + objA.objB.objC.objD.objE.prop4;

   ......
   ......
}

or

var objonlyE = objA.objB.objC.objD.objE
if (objonlyE != null)
{
   objX.var1 = objonlyE.prop1;
   objX.var2 =  objonlyE.prop2;
   objX.var3 = objonlyE.prop3 + objonlyE.prop4;
   ......
   ......
}

The second one is better because you never know what's hiding behind a '.'. 第二个更好,因为你永远不知道隐藏在'。'背后的是什么。 It could be a database call or some other expensive operation. 它可能是数据库调用或其他一些昂贵的操作。

Performance doesn't come into it, as property access is going to be fast (and even if it isn't, it makes little difference if you access the same properties in the same order). 性能不会进入它,因为属性访问速度会很快(即使不是这样,如果以相同的顺序访问相同的属性,它也没什么区别)。

Maintainability and readability are the issues and in that regard, your second option is much better. 可维护性和可读性是问题,在这方面,您的第二个选择要好得多。

Read about the Law of Demeter : 阅读得墨忒耳定律

The Law of Demeter (LoD) or Principle of Least Knowledge is a design guideline for developing software, particularly object-oriented programs. Demeter法则(LoD)或最小知识原则是开发软件,特别是面向对象程序的设计指南。 In its general form, the LoD is a specific case of loose coupling. 在一般形式中,LoD是松耦合的特定情况。

第二个更容易使用...所以,更好,因为你不会一次又一次地重复你的代码......

I prefer second approach, it is much more readable. 我更喜欢第二种方法,它更具可读性。 In terms of performance it should be unnoticeable, that is in case of regular variables / properties. 在性能方面,它应该是不明显的,即在常规变量/属性的情况下。 If there are some performance heavy operations hidden under properties then you should also use second version as it will be faster. 如果在属性下隐藏了一些性能繁重的操作,那么您还应该使用第二个版本,因为它会更快。

In second approach you a have less place for programmer mistakes for example in fist one you could do the following mistake: 在第二种方法中,您可以减少程序员错误的位置,例如在第一种方法中,您可能会犯下以下错误:

objX.var1 = objA.objB.objC.objD.objE.prop1;
objX.var2 = objA.objB.**objU**.objD.objE.prop2;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM