[fpc-pascal] for loop vs while loop

Jürgen Hestermann juergen.hestermann at gmx.de
Wed Feb 1 13:16:36 CET 2017


Am 2017-02-01 um 12:49 schrieb Graeme Geldenhuys:
 > Just curious (been in a discussion with somebody else). Is there a
 > performance difference between a FOR loop and a WHILE loop?
 > Not sure if it will make a difference, but the usage is with three
 > nested loops, iterating over some 300,000 plus data points in total.

I think that in general a FOR loop *can* be faster than a WHILE loop
because the iterator variable will be held in a register (if possible)
and its start and end values will be calculated only once.

Also, because the iterator variable will be incremented (or decremented)
by a constant value it helps the compiler to speed it up further.

If the major time of the loop is needed for the loop body it will not make much difference of course.

Still it makes sense to always use a FOR loop if possible.




More information about the fpc-pascal mailing list