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;
}
tldr; they are semantically equivalent and perform identically.
There is only one variable called
objectin both cases presented. ActionScript, like JavaScript, “hoists” declarations. That is,varis really just a function-scoped annotation. This differs from C and Java where a new scope (and thus new variable) would have been created in the 2nd case.There is no difference in AS, however. The engine effectively treats the 2nd code identical to the first. (That being said, I prefer to “keep the
varclose” to where it is used, while understanding it is not relevant to the scope and has no bearing on performance.)See Action Script 3.0: Variables and, the Scope section in particular:
Happy coding.