Talk:Loop-invariant code motion
The page originally had the following:
This can then be further optimized, leading to less overall executed code for larger values of maxval and/or smaller values of calcval.
int calcval = (4+array[k])*pi+5;
j = j + integer_part((maximum - 1 - j) / calcval) * calcval;
However, that transformation is not "loop-invariant code motion". In any case it is not obviously correct when maximum is near overflow (well, OK, maybe it's undefined behaviour then, but suppose that j was unsigned). --DavidHopwood 01:16, 29 January 2007 (UTC)
As of 10 Apr 2007, this article has:
while (j < maximum - 1) { j = j + ( 4 + array[ k ] ) * pi + 5; }The calculation of maximum - 1 and (4+array[k])*pi+5 can be moved outside the loop.
This makes an assumption that the program in question is not threaded. Otherwise, what would be the guarantee that no other thread would modify the value of maximum while this thread was executing that loop? (As for the pre-calculation?)
--Kevin
Non-compiler use
This sort of optimization is frequently seen in JavaScript, where iterating over an array or a list of DOM nodes can often be sped up by precalculating the length of the array or node list either outside the loop or (more commonly) in the initialization of the loop variables (e.g., for(var i=0, max=someList.length; i < max; i++)
instead of for(var i=0; i<someList.length; i++)
, avoiding the repetitive computation -- in some JavaScript implementations -- of someList.length
). If anyone thinks this would be a useful addition to the article, I'll dig up some references and put it in. Ubernostrum 08:43, 5 July 2007 (UTC)