Tip of the week#1: Looping performance

Never use two loops if one loop will suffice.

Example:

for(i=0; i<5; i++)
{
   /*Do something 1*/
}

for(j=0; j<5; j++)
{
   /*Do something 2*/
}

In the above example, first and the second “for” loop will execute 5 times each. That is the total of 10 times.

The performace of the above code can be optimized by using only one for loop as follows:

for(i=0; i<5; i++)
{
   /*Do something 1*/
   /*Do something 2*/
}

The above loop will be executed only 5 times. Thus the time required for execution is reduced.

Note: If the instructions in the loop are too much, 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.

If you are accessing memory (e.g. an array) in both of your loops, using a single loop may be 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.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *