High performance looping

This tip submitted by Rachana on 2006-07-19 04:16:25. It has been viewed 24002 times.
Rating of 6.8 with 234 votes



Never use two loops where one will suffice:
for(i=0; i<100; i++)
{ stuff();
}
for(i=0; i<100; i++)
{
morestuff();
}
It would be better to do:
for(i=0; i<100; i++)
{ stuff();
morestuff();
}

Two factors may impact the performance of loops: one is that if you do a lot of work in the loop, it might not fit into your processor's instruction cache. In this case, two separate loops may actually be faster as each one can run completely in the cache.

The other factor is that if you are accessing memory (e.g. an array) in both of your loops, using a single loop may b faster because the most recently used parts of the array can be kept in the CPU (or for disk IO, the disk) cache. If you have two loops, you won't be able to take advantage of that caching.



More tips

Help your fellow programmers! Add a tip!