.net - are two loops more costly than one loop regrouping the code of the two ones in C#? -


This may be a silly question but ...

Refactoring my code, I Question: I can not find any answer:

I have no object MyDumyObject with string properties containing Foo and bar

assuming that I have MyDumyObject named

  foreach The collection is in MyDumyObject obj MyDumyCollection) {obj.Foo = "fooooooooo"; Obj.Bar = "baaaaaaar"; }   

equals

  foreach (MyDumyObject obj in MyDumyCollection) {obj.Foo = "fooooooooo"; } Foreign currency (MyDumyObject obj in MyDumyCollection) {obj.Bar = "baaaaaaar"; }   

?

I'm feeling: No, but I've been cheated by C # and the way C # compiler works more than once, so I'm careful now with my beliefs, and I would be happy to confirm or deny

Helpful question:

<< p>

  foreach (MyDumyObject obj in MyDumyCollection) {obj.Foo = "fooooooooo"; // .... obj.Foo = "foooooooooooooooooooooooooo"; }   

equals

  foreach (MyDumyObject obj in MyDumyCollection) {obj.Foo = "fooooooooo"; } // foreach (MyDumyObject obj in MyDumyCollection) {obj.Foo = "foooooooooooooooooooooooo"; }   

?

Two ends are more expensive than a loop Loop is more expensive than the loop overhead, assuming the code inside the statement, it will not make any difference - but in your case the overhead looks very important, so yes two loops are more expensive and each enumerator is ready for each of them. To be done and you need to calculate once for each item in the collection The next item will go on (although lists access a simple index [] ) - twice to the upper part with two loops .

Also keep in mind that where you can not be repeated and can not be repeated, from one network, but between these cases and in between - in-memory collections (like list & lt ; T & gt; ) This generally does not apply.

Typically readability versus micro-optimization - I really do not think the loop overhead matters a lot.

Comments