Loop-invariant code motion: Difference between revisions

Content deleted Content added
Dcoetzee (talk | contribs)
cat, link, detail
No edit summary
Line 1:
'''Loop-invariant code''' in an imperative [[Computer programming|programming]] language consists of statements which could be moved to before the loop (if the loop always terminates), or after the loop, without affecting the semantics of the program. As a result it is executed less often, providing a speedup. '''Loop-invariant code motion''' is a [[compiler optimization]] which performs this movement automatically.
 
==Worked Example==
If we consider the code sample, two optimization possibilites can be applied.
<code><pre>
while (i < maximum - 1)
{
j = j + (4+array[k])*pi+5;
}</pre></code>
 
The calculation of <pre>maximum - 1</pre> and <pre>(4+array[k])*pi+5</pre> can be moved outside the loop, and precalculated, resulting in something similar to:
 
<code><pre>
int maxval = maximum - 1;
int calcval = (4+array[k])*pi+5;
while (i < maxval)
{
j = j + calcval;
}</pre></code>
 
{{compu-stub}}
[[Category: Compiler optimizations]]