开发者

Is it a good practice to put independent methods under a loop or separate loops?

for example

  for (int i=1;i<10000;i++)
  {
       j++;
       k++;
  }

or

  for (int i=1;i<10000;i++)
  {
       j++;
  }
  for (int i=1;i<10000;i++)
  {
       k++;
  }

Note 1: in c# is it still better to use ++i instead of i++?

Note 2: A good thing that if we spilt a large loop into separate simple loops is th开发者_开发技巧at then we can transform it into Linq form, such as enumerable.range(1,10000).forall(x=>j++) so in the lambda expression or delegate i don't have to put multiple statements together.


1: no difference in performance; if you are using it as part of an expression it simply gives you the flexibility to use either form

2: LINQ gains you little here; you're still ultimately doing the same loop (unless you switch to Parallel, in which case your ++ is broken) - but if you add LINQ you're adding overheads to do it.

re how many loops; in this case I'd do one loop - but define it logically in terms of the bounds etc. Unless either of the operations is complex, in which case maybe split that out to a separate method.


(1) almost the same

(2) Use one loop if the code in the loop is quite simple, like i++ or j++. Note that using separate loops for 2 complex methods is probably faster than one loop:

//better and faster
for (int i = 1; i < 1000; i++)
{
    OneThing(i);
}
for (int i = 1; i < 1000; i++)
{
    AnotherThing(i);
}

Separated loops improves the hit rate of the registers. If you put them in one loop, the time reduced by 1000 loops is less than the more time cost by register miss.


To answer your first question: the compiler takes care of that for you, and whether it is better depends on the usage as the behaviour is slightly different. I think the compiler emits ++i in the case of for loops, but for for loops it also makes no difference.

To answer your second question: there is no concept of best practice in this case. Your lambda can do more than one action anyway. Write the code that is easiest to understand and maintain.


The same concept of post and pre increment holds good in c# as well.

And seperating into multiple loops as you ahve shown shall create more over head coz now your iterating twice than once before.


I would say use the approach that is easier to read and understand.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜