简体   繁体   中英

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. In its general form, the LoD is a specific case of loose coupling.

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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