Test this code in Flash:
var i:int = 0;
for (var j:int = 0; j < 5000000; j++)
{
i=i+1;
}// use about 300ms.
i = 0;
for (var j:int = 0; j < 5000000; j++)
{
i++;
}// use about 400ms
i = 0;
for (var j:int = 0; j < 5000000; j++)
{
++i;
}// use about 400ms too
Why is i=i+1 faster in ActionScript 3 when it’s slower in others?
Sorry,I make some mistake.The code above use the same time.
but if put it into function,and the result will be different.
var i:int;
var j:int;
var startTime:Number;
function func1():void
{
i = i + 1;
}
function func2():void
{
i++;
}
startTime = getTimer();
i = 0;
for (j = 0; j < 10000000; j++)
{
func1();
}
trace(getTimer() - startTime);//5 times:631,628,641,628,632
startTime = getTimer();
i = 0;
for (j = 0; j < 10000000; j++)
{
func2();
}
trace(getTimer() - startTime);//5 times:800,814,791,832,777
Where your loop is situated can have a large impact on performance. If your loop is inside a function, Flash will perform calculations using local registers. The loop containing
i++produces thus the following opcodes:The loop containing
i = i + 1produces the following:i++is faster thani = i + 1here since inclocal_i modifies the register directly, without having to load the register onto the stack and saving it back.The loop becomes be far less efficient when you put it inside a frame script. Flash will store declared variables as class variables. Accessing those requires more work. The
i++loop results in the following:The
i = i + 1version is somewhat shorter: