2

Should I declare the _mcContainer var before the loop or no? (performance increase?)

for(var i:uint = _startIndex; i <= _endIndex; ++i){    
    var _mcContainer:MovieClip = _mcParent["i_" + _position];
}

or

var _mcContainer:MovieClip;
for(var i:uint = _startIndex; i <= _endIndex; ++i){
    _mcContainer = _mcParent["i_" + _position];
}

?

6
  • second option is faster, have a look at this: rozengain.com/blog/2007/05/01/… Commented Nov 9, 2010 at 17:05
  • @george, which part of that page relates to this question? I'm having trouble finding anything. Commented Nov 9, 2010 at 17:09
  • @spender "We can also speed up the loop by storing the array’s length in a variable outside of the loop" before 'Constants from other classes'...u are right...not in plain sight Commented Nov 9, 2010 at 23:55
  • @george-profenza but array's length is different case cause there if you don't use a var to reference to the length each time your loop will call need to get the array length over and over again. But in my case I was wondering does it change something if I declare the variable and it's type before the loop so on looping it wouldn't declare new variable each time. Commented Nov 9, 2010 at 23:59
  • ok, I see...in your case, as @spender mentioned it shouldn't make a difference Commented Nov 10, 2010 at 0:25

1 Answer 1

6

It's not hard to test...

...however according to the docs, it shouldn't make any difference because variable declarations are hoisted to the top of the method block anyway.

From the docs:

An interesting implication of the lack of block-level scope is that you can read or write to a variable before it is declared, as long as it is declared before the function ends. This is because of a technique called hoisting , which means that the compiler moves all variable declarations to the top of the function.

Sign up to request clarification or add additional context in comments.

3 Comments

Good point. This has bitten me several times when I was developing in AS3. Other compilers like C++ (and even Java) recognize using a variable before it is declared as a compile-time error.
From the Flex coding conventions: opensource.adobe.com/wiki/display/flexsdk/… i thought that i've to declare variables only before they are used and that would increase performance, but thanks to your docs reference i see it does not. :] Thanks!
Having variables declared after they are used reduce code legibility, in my opinion. They should be declared before they are used - in worst case in the same line. But not later.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.