Loop Unrolling

A loop with a constant known maximum can be unrolled very easy. In most cases it does not make sense to unroll a loop manually because maintaining the code will require much more work. This is usually a job which the compiler can perform in its optimization phase.

Normal Version
const x: Number; for( var i: Number = 0; i < 5; ++i ) { 	x = i * i; 	trace( x.toString ); }

Unrolled Version
const x: Number; x = 0.0 * 0.0; trace( x.toString ); x = 1.0 * 1.0; trace( x.toString ); x = 2.0 * 2.0; trace( x.toString ); x = 3.0 * 3.0; trace( x.toString ); x = 4.0 * 4.0; trace( x.toString );

Now it is be possible to recude that code even more.

const x: Number; x = 0.0; trace( x.toString ); x = 1.0; trace( x.toString ); x = 4.0; trace( x.toString ); x = 9.0; trace( x.toString ); x = 16.0; trace( x.toString );

The next step in this example is of course removing the x variable.

trace( ( 0.0 ).toString ); trace( ( 1.0 ).toString ); trace( ( 4.0 ).toString ); trace( ( 9.0 ).toString ); trace( ( 16.0 ).toString );

The code is now reduced and would execute faster. But unrolling a loop is something which only begins to make sense with a lot of iterations. Therefore it does not make sense to apply this technique manually.