3.4.1 Efficient loops

This might seem rather trivial, in how many ways can you mess up a loop
anyway? Well... actually, quite a few. Let's start with the most common
mistake. Assume you have a large array, let's call it 'big_arr', and
let's assume you want to loop over all elements in that array, what do
you do? "Simple!", you exclaim, "A 'for' loop, of course!". Sure... but
how do you write it? Well, the most common implementation usually looks
something like this:

int i;
for (i = 0; i < sizeof(big_arr); i++)
{
// Here we do something with the array
}

Ok... now why is this bad? Well, if you review the chapter on how the
for statement works, you'll find that the three parts inside
the round brackets actually gets executed. The first one once at the
start, the second (or middle) part every time the loop is run
and the third part also every time the current loop is finished.

This obviously means that the sizeof() function gets executed
every time the loop is run. rather a waste of time given the fact that
the array hardly is intended to change size. If it was, that would have
been another matter, but as it isn't... No. Write like this instead:

See? The variables 'i' and 'sz' gets assigned their respective values
at the start of the loop, and only then. The counter 'i' gets set to 0
and the size variable 'sz' gets set to the size of the array. During the
entire loop after that, 'i' is compared with 'sz' instead of repeatedly
recompute the size of the array.

Believe it or not, this is a very common mistake, all people do it. While
the savings in doing as I suggest might not seem that great, well...
multiply this small gain in one loop by all the loops in the mud and all
the number of times that those loops are run and you'll end up with quite
a big number. The added cost in doing this is one local variable, which
is a small enough price to pay.

Keep this general problem in mind since a lot of cases don't use arrays
perhaps, but mappings or other general containers of items you want to
loop through. The solution apart from specifics in identifying the size
of that container is always the same.