Loop-invariant Code Motion - Example

Example

If we consider the following code sample, two optimizations can be easily applied.

for (int i = 0; i < n; i++) { x = y + z; a = 6 * i + x * x; }

The calculations x = y + z and x * x can be moved outside the loop since within they are loop invariant— they do not change over the iterations of the loop— so the optimized code will be something like this:

x = y + z; t1 = x * x; for (int i = 0; i < n; i++) { a = 6 * i + t1; }

This code can be optimized further. For example, strength reduction could remove the two multiplications inside the loop (6*i and a), and induction variable elimination could then elide i completely. Since 6 * i must be in lock step with i itself, there is no need to have both.

Read more about this topic:  Loop-invariant Code Motion

Famous quotes containing the word example:

    Our intellect is not the most subtle, the most powerful, the most appropriate, instrument for revealing the truth. It is life that, little by little, example by example, permits us to see that what is most important to our heart, or to our mind, is learned not by reasoning but through other agencies. Then it is that the intellect, observing their superiority, abdicates its control to them upon reasoned grounds and agrees to become their collaborator and lackey.
    Marcel Proust (1871–1922)