开发者

Looking for opinions on when to unwind loops with if statements

I'm wondering when (if ever) I should be pulling if statement out of substantial loops in order to help optimize speed?

for(i=0;i<File.NumBits;i++)
  if(File.Format.Equals(FileFormats.A))
    ProcessFormatA(File[i]);
  else
    Pro开发者_开发知识库cessFormatB(File[i]);

into

if(File.Format.Equals(FileFormats.A))
  for(i=0;i<File.NumBits;i++)
    ProcessFormatA(File[i]);
else
  for(i=0;i<File.NumBits;i++)
    ProcessFormatB(File[i]);

I'm not sure if the compiler will do this type of optimization for me, or if this is considered good coding practice because I would imagine it would make code much harder to read / maintain if the loops were more complex.

Thanks for any input / suggestions.


When you are finished the code and the profiler tells you that the for loops are a bottleneck. No sooner.


If you're actually processing a file (i.e. reading and/or writing) within your functions, optimizing the if is going to be pointless, the file operations will take so much longer, comparatively, than the if that you won't even notice the speed improvement.

I would expect that a decent compiler might be able to optimize the code - however, it would need to be certain that File.Format can't change in the loop, which could be a big ask.

As I always like to say, write first, optimize later!


Definitely code for maintainability and correctness first. In this case I would be inclined to suggest neither:

for(...)
    ProcessFormat(File, Format);

Much harder to mess up if all the checks are in one place. You do a better job of confusing your optimizer this way, but generally you want correct code to run slowly rather than incorrect code running quickly. You can always optimize later if you want.


The two perform the same and read the same, so I'd pick the one that has less code. In fact, this example you give hints polymorphism might be a good fit here to make code simpler and short still.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜