Why infinite loops are faster than finite loops?

Stanislav Blinov stanislav.blinov at gmail.com
Sat Jun 20 21:48:45 UTC 2020


On Saturday, 20 June 2020 at 21:11:57 UTC, tastyminerals wrote:
> I am not sure that this is a question about D or a more general 
> one. I have watched this nice presentation "Speed Is Found In 
> The Minds of People" by Andrei: 
> https://www.youtube.com/watch?v=FJJTYQYB1JQ&feature=youtu.be?t=2596 and on 43:20 he says that "push_heap" is slow because of structured loops and finite for (throughout the presentation Andrei shows algorithm examples with infinite loops). I wonder why is that? Is it because the finite loop needs to keep track of the number of iterations it performs? Wouldn't the compiler optimize it better than the infinite one because it knows the number of iterations the for loop needs?

He explains it there and then. When the number of iterations is 
*small*, overhead of each iteration can be significant. He's not 
talking about known *number* of iterations, but known exit 
conditions. If you put those exit conditions in the loop's test, 
you have to go through till the end and then test them, while if 
you put the tests in the loop body you can bail early and skip 
some unnecessary operations.

Don't take it too literally. As he himself says "always use 
infinite loops, except in most cases" :)

He's simply emphasizing the importance of looking at code 
critically and not taking things for granted.


More information about the Digitalmars-d-learn mailing list