beware of loop invarinatsThis tip submitted by Iain on 2005-02-27 14:43:27. It has been viewed 45824 times.
Rating of 5.8 with 209 votes
Be aware of loop invariants and how they can affect code efficiency . An example:
If you have code within a loop tha uses non-varying variables:
for(i = 0; i < 100; i++)
total = i + x + y;
} //end for
as you can see, x and y are not variable within the loop and so it is much more efficient to code the loop as follows:
total = x + y;
for (i = 0; i < 100; i++)
total += i;
this is because the loop does one less addition on each loop cycle.
Help your fellow programmers! Add a tip!