Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable declaration performance on loops in Actionscript 3

Despite all known blogs about this issue i always doubt some results and my personal tests shows that the well-said standard isn't the best.

Declaring variables inside the loop, to keep them close to its scope and make it faster to be reached by the method but allocating more memory or declaring outside the for scope to save memory allocation but increase processing to iterate in a distant instance.

My results shows that method B is faster(sometimes), i want to know the background around this.

results vary and im not a bit-brusher guru.

So what you guys think about it?

Method A

var object:Object = new Object();
var loop:int = 100000
for (var i:int = 0; i < loop; i++)
{
    object = new Object();
    object.foo = foo;
    object.bar = bar;
}

OR

Method B

var loop:int = 100000
for (var i:int = 0; i < loop; i++)
{
    var object:Object = new Object()
    object.foo = foo;
    object.bar = bar;
}
like image 439
Conrado Souza Avatar asked May 24 '12 18:05

Conrado Souza


1 Answers

AS3 compiler moves all the variable declarations to the top of the method which is called variable hoisting. And the minimum scope for a variable is a complete method. Your method B is equivalent of the following:

var loop:int = 100000;
var i:int;
var object:Object;
for (i = 0; i < loop; i++) {
    object = new Object();
    object.foo = foo;
    object.bar = bar;
}

Note that it only moves the declaration up, not the associated assignment with this. This is the reason you can declare a variable after using it. For example try this code:

trace(a);
var a:int = 10;
trace(a);

This will compile. It's because this code is equivalent of:

var a:int;
trace(a);
a = 10;
trace(a);

This is also the reason that you will get a duplicate variable declaration warning with the following code:

for (var i:int = 0; i < m; i++) {

}
for (var i:int = 0; i < n; i++) { // i is already declared once

}

The concept of variable scope in AS3, JS is different from that of C, C++, Java etc.

like image 156
taskinoor Avatar answered Sep 21 '22 08:09

taskinoor