Bhan said:
I heard for(i=0;i<20;i++)
{
do-something;
}
Can be optimized.
Is this can really optimized by an equivalent for loop or with while or
do while loops?
The above is exactly equivalent to:
i = 0;
while (i < 20) {
do-something;
++i;
}
It is obvious that the first time the condition is tested (before entering
the loop) it will be true, so there is no need to actually do the test. The
test can be moved to the bottom of the loop:
i = 0;
do {
do-something;
++i;
} while (i < 20);
If the value of i is not used except to control the number of iterations,
the following may be better in some cases:
i = 20;
do {
do-something;
} while (--i);
Another possibility already mentioned is loop unrolling. This increases code
size but may not actually increase performance. In particular, unrolling
tests (eg if "do-something" contains one or more "if" statements) may
actually decrease performance.
The loop may be partially unrolled, eg:
/* if the value of i is used: */
i = 0;
do {
do-something;
++i;
do-something;
++i;
} while (i < 20);
/* or, if the value of i is not used */
i = 0;
do {
do-something;
do-something;
++i;
} while (i < 10);
Or the loop may be fully unrolled, in which case there is no loop anymore.
However, all of this is best left to the compiler to figure out, until and
unless such optimisation helps a previously-identified performance
bottleneck.
Alex