Mar
18
2010

Optimizing Your ActionScript Code

Optimizing your code is very important, we can gain performance increase with very little costs, but we have to remember that the most important think for a Developer is to easily understand his code. Bellow I post some techniques to improve the performance of your AS3 code, remember if some of those shortcuts are not easily readable for you maybe it’s not the time to use them. For example I wont use the strange (for me) if statement structure ‘? : ;’ because each time I see it I have to think how this actually work, anyway here are some tips:

  • Creating Object:
    var obj:Object = {} ;

    Not:

    var obj:Object = new Object();
  • Createing Arrays:
    var arr:Array= [] ;
    

    Not:

    var arr:Array= new Array();
    
  • Fastest way to copy an array:
    var copy : Array = sourceArray.concat();
    
  • Use integers for iterations (or event better uint’s):
    for (var i: int = 0; i < n; i++) { }
    

    Not:

    for (var i: Number = 0; i < n; i++) { }
    
  • Avoid calculations and method calls in loops:
    var len : int = myArray.lengh;
    for (var i=0;i<len;i++){};
    

    Not:

    for (var i=0;i< myArray.lengh;i++){ };
    
  • Use ? : ;
    b = (a>2) ? 1 : 3;
    

    Not:

    if(a > 2)
    {
        b = 1
    }
    else
    {
       b = 3
    }
    
  • In classes using:
    public var _x:Number;
    

    is much faster then using (in terms of code execution):

    private var _x:Number;
    
    public function get x():Number {
    return _x;
    }
    public function set x(n:Number) {
    _x=n;
    }
    
  • Using in line code is faster the calling additional functions:
    public function f1(){
    
    //do something
    
    //do something more
    
    }
    

    Not:

    public function f1(){
    
    //do something
    
    f2();
    
    }
    
    public function f2(){
    
    //do something more
    
    }
    
  • When creating variables:
    var a:Number=4
    

    is better then

    var a=4;
    

    also when creating multiple variables, use:

    var a:Number, b:Number, c:Number;

    instead of:

    var a:Number;
    
    var b:Number;
    
    var c:Number;
  • Use multiply instead of divide:
    x * 0.5;
    

    is better then

    x / 2;
    
  • Use the strongest typing possible:
    var pt:Point = new Point(x,y);
    

    Not:

    var pt:Object = {x:x, y:y};
    
  • Use implicit type casting:
    var pt:Point = points[i];
    

    Not:

    var pt:Point = points[i] as Point;
    
  • Exception: iterators:
    pt = points[uint(i * 2)];
    

    Not:

    pt = points[i * 2];
    
  • Conditional priority:
    if (usuallyFalse && expensiveTest())
    

    Not:

    if (expensiveTest() && usuallyFalse)
    
  • Calling errors is very expensive:
    if(isNull) {
    isNull.x = 3;
    }
    

    Not:

    try {
    isNull.x = 3;
    } catch (e:*){}
    
  • Avoid using with:
    var g:Graphics = sprite.graphics;
    

    Not:

    with (sprite.graphics) {  }
    
  • Always clean up idle listeners enterFrame, timer, mouseMove
  • Callbacks are faster than events for assignment & dispatch. Bubbling events are even slower
  • Call methods directly instead of through a reference. Avoid anonymous functions
  • Use bitwise tricks (see examples in the useful links at the bottom of this post)
  • Static functions are slower then non-static.

Here are some useful links and posts that I used to create this post:
http://gskinner.com/talks/quick/
http://opensource.adobe.com/wiki/display/flexsdk/Coding+Conventions
http://lab.polygonal.de/2007/05/10/bitwise-gems-fast-integer-math/
http://alexgblog.com/?p=392

Special Thanks to ActiveDen community and of course Grant Skinner for his awesome presentation.

If you know any other resources or techniques please post them!

Related Posts

About the Author: Kuba Gaj

Hi, my name is Kuba and I am the founder of massiveProCreation. I am interested in almost everything that is connected to technology (specially Adobe Flash). If you have any questions or suggestions please feel free to contact me :)

20 Comments + Add Comment

  • Thanks to AmaDiver from reddit:
    For a really detailed and referenced article on AS3 optimization, check out: http://www.stephencalenderblog.com/?p=7

  • I hate code like this : b = (a>2) ? 1 : 3;

    It’s requires more strain to read and understand, especially in real life, where statements aren’t as simple as this.

  • Me too ;) Thats why I never use this :)

  • Should have read more before posting, but :

    There are some really nice tips there, but also some I don’t feel the speed boost makes up for the reduced readability and reusability:

    * Using callbacks instead of events makes your objects dependent on the parent code

    * is not using getters and setters worth the speed profits?

  • I always use getters and setters, and I’m not saying you shouldn’t I’m just saying that cods executes faster without them ;)

  • Great summary. Thanks for putting it together.

  • Decent list, but a few myths on there:

    - uint is not faster in loops, and on in Player v9 it was actually slower

    - array.slice() is faster than array.concat()

    - multiple variables on a single line isn’t faster or slower

    - explicit type casting, e.g. Type(instance), is just as fast as implicit type casting; it’s *conditional* type casting (using the as operator) that’s slow because it translates to “instance is Type ? Type(instance) : null”

  • All of this is notable in one version of the flash player, if the runtime changes/improves different methods will be faster than others and this article will filled with untruths. Write code that is readable and follows the principles of object orient programming, use design patterns and stay away from anti-patterns. It is Adobe’s job to improve the speed of the runtime, it is your job to write clean code.

    And ternary statements, bitwise operators and regular expressions are different ways to program but they are better in many cases if you learn what the characters mean then you will think about them as being powerful tools in your tool chest rather than oddities, they are part of the language for a reason.

  • Yes, thats true Tyler I agree in 100% with you ;)

  • I find it hard to believe that the first 2 examples could really have a measurable speed impact.

  • There’s no evidence provided for any of this. It all looks a bit made up. As has been mentioned, why are the first two faster? The next two are questionable (see Troy’s post)? The 5th one is neither a calculation nor a method call (it’s a property)? Why is the sixth actually faster? And on and on…

  • Why did not note reproduces the information

  • Darren if you don’t know why they are faster maybe look into Grant Skinner’s presentation. Then you will know why they are faster. I agree only on the first two, I don’t understand why they are faster but I saw on some benchmarks that they are. Most of those examples is drawn from Grant’s presentation and he knows what he is talking about. For example why you should “avoid calculations and method calls in loops” because otherwise Flash Player has to count the length of the array in each iteration of the array, yes it’s that easy ;)

  • Maybe some statements are faster. But how much do you gain by these “optimizations” in return for hard maintainable code?

  • I dont see any hardness in this code except the strange if statement…

  • Very nice list!

  • Can you demonstrate examples ? Do you have concrete studies on what you are telling ?

    Have you looked the binary file to say not using something ?

    Did you know that implicit getter/setter was inline function ? like in C++ ? so it’s not faster, its replaced in the code before actually compile it.

    The use of b = (a>2) ? 1 : 3; is not a optimisation at all. It sometimes easier to write code like that for trivial functions.

    For example: ((thumbRange != 0) ? (y / thumbRange) * range : 0)

    It means that if thumbRange equals 0, as you cannot divide by zero, it return 0. This is very useful in this case. In other case this is not a good idea, but in both case its the same speed.

    I would like to have more scientific facts to justify what you are saying in this article. Otherwise, its true that calling functions, using constructors, in a virtual machine environment is costly in term of processor.

  • I’m sorry I have no real facts to confirm the inline getter and setter. Its probably what I would have done if I was a developper of the AVM2 but its possible that it hasn’t been done as an optimization.

    You can have a deeper look into the AVM2 specs here: http://www.adobe.com/devnet/actionscript/articles/avm2overview.pdf

    About the Flash 10 specs here: http://www.adobe.com/devnet/swf/pdf/swf_file_format_spec_v10.pdf

  • @Sylvian Maybe you should read the post carefully and go trough the links I posted at the bottom, all of those optimizations are from there…

  • @Sylvian About the getter and setter I am only saying its faster to call a public var then setting it through getter and setter… and I think this is logic ;o

Leave a comment

Become an Author

We are looking for Authors, if you have a Flash (or related) knowledge and you want to share it with the community on our blog please contact us.

Partners