For-loop efficiency: merging loops

后端 未结 7 597
野趣味
野趣味 2021-01-04 19:46

I have always had the idea that reducing the number of iterations is the way to making programs more efficient. Since I never really confirmed that, I set out to te

7条回答
  •  星月不相逢
    2021-01-04 20:07

    I believe it's more complex than that. Whether a single loop is faster than multiple loops depends on a few factors.

    The very fact that program iterates over a set of data costs you something (incrementing the iterator or index; comparing the iterator/index to some value that lets you know that the loop is finshed) so if you divide a loop into a couple of smaller loops you pay more for iterating over the same set of data multiple times.

    On the other hand if the loop is smaller then optimizer has easier job and has more ways to optimize the code. CPU also has possibilities to make loops run faster and usually it works best with small loop.

    I've had pieces of code which became faster after dividing a loop into smaller ones. I also wrote algorithms which turned out to perform better when I merged a couple of loops into one loop.

    Generally there are many factors and it's difficult to predict which one dominates so the answer is you should always measure and check a few versions of code to find out which one is faster.

提交回复
热议问题