For-loop efficiency: merging loops

后端 未结 7 532
野趣味
野趣味 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:33

    The thing you gain from a single loop, is the fact that you lose the incrememnting of the loop variable. So in a case like this where the content of the loop is so trivial, that assignment (and test) makes a big difference.

    What your example fails to take into consideration also; is that contiguous memory access will often be faster than random access.

    In a function where the loop takes much longer (try putting a sleep in rather than assignment) you'll find that the difference works it's way into not a lot.

    THE way to get performance improvements is to start with the Maths - the right algorithm will always buy the biggest improvements. This is done, ideally, before finger hits keyboard.

提交回复
热议问题