Avoiding Multiplications In Loops

From ActionScriptWiki

Jump to: navigation, search

Multiplications in loops are often not necessary if one of the factors is a constant value.

[edit] Wrong version

value is the result of i multiplied by the constant factor 10. The multiplication is unnecessary.

const n: int;
var i: int;

var value: int;

for( i = 0; i < n; ++i )
{
	value = i * 10;
	trace( value.toString() );
}

[edit] Correct Version

Since 10 is a constant factor and a multiplication is nothing else than a repetitive addition of the same summand it is possible to get rid of the expression i * 10 which is more expensive than a simple addition.

const n: int;
var i: int;

var value: int;

for( i = 0; i < n; ++i )
{
	trace( value.toString() );
	value += 10;
}

Note: value is now modified after the call to trace so that it is zero in the first iteration. It is also important to note that there is no access of i in the body of the loop. A modern compiler (not the ActionScript compiler) could unroll this sort of loop pretty easy.

Personal tools