Variable declaration performance on loops in Actionscript 3

actionscript-3, low-level, performance

Solution

tldr; they are semantically equivalent and perform identically.

There is only one variable called `object` in both cases presented. ActionScript, like JavaScript, "hoists" declarations. That is, `var` is 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 `var` close" 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:

The scope of a variable is the area of your code where the variable can be accessed by a lexical reference... In ActionScript 3.0, variables are always assigned the scope of the function or class in which they are declared.

Happy coding.

Problem

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; } ```

Original source