More performance tuning in Actionscript 3

May 1st, 2007

I noticed a link yesterday over at RozenGain’s Blog about performance tuning, and I might have a couple things to add to the list as well. Go look at his blog first, as they’re not as obscure as mine :). He’s also got links to other performance tuning posts that are extremely helpful as well. If you’re working with bitmaps a lot, check out one of my previous blog posts about bitmap performance tuning. The methods below are for squeezing every last drop of cpu performance out of the runtime (sometimes at the cost of memory albeit very little memory), and is really only designed if you’re trying to squeeze 1 millisecond off your Event.ENTER_FRAME scripts. Here goes:

Create constants for commonly used objects, such as new Point(0,0), new Rectangle(0,0,320,240), etc. This reduces overhead of creating new objects.

Often when dealing with bitmaps, we’ll use new Point(0,0) quite often, or filter rectangles. If these stay constant, store them as a variable and re-use them as often as possible. Each of the following examples use 100,000 iterations.

// Method A: Using new Point(0,0)

// 100k loops: 75ms
new Point(0,0);

// Method B: Storing a constant and re-using it
private static const POINT:Point = new Point(0,0);

// 100k loops: 8ms
POINT;

838% faster

Reduce pointers to static class names as much as possible, use package variables and functions instead.

Many times we’ll use a StringUtils class and store all our methods within that StringUtil class, however, doing a lookup on the class name is more expensive than if the functions were located in a package. Now this is also good for the swf size, because if you’re not using all the methods within StringUtils, you won’t compile those functions. For instance:


// MethodA: Static variable in class

// 100k loops: 15ms
SomeClass.somevar;

// MethodB: Package variable
package somepackage{
	public const somevar:int;
}

// 100k loops: 8 ms
somevar;

// look-up is similar to the variable being local
66% faster

Store getter properties as local variables when using them more than once in a method (such as .graphics, .transform)

// MethodA: Using a getter directly

// 100k loops: 202ms
somesprite.graphics.clear();
somesprite.graphics.beginFill(0x000000);
somesprite.graphics.drawRect(0,0,10,10);
somesprite.graphics.endFill();

// MethodB: Store getter as local variable, then execute

var n:Graphics = sprite.graphics;

// 100k loops: 22 ms
n.clear();
n.beginFill(0x000000);
n.drawRect(0,0,10,10);
n.endFill();

// 18% faster

Or use both those methods, package variable vs getter (this.stage and STAGE); I like this method too because i can reference stage within a constructor as well.


// MethodA: getter

// 100k loops: 17ms
this.stage;

// MethodB: Package variable
package somepackage {
	public var STAGE:Stage;
}

STAGE = this.stage;

// 100k loops: 8 ms
STAGE;

// look-up is as similar to the variable being local
113% faster

Create custom reflection methods instead of using: getDefinitionByName(getQualifiedClassName(object))


// MethodA: utils reflection
// 100k loops: 503ms
var someclass:Class = getDefinitionByName(getQualifiedClassName(someObject));

// MethodB: getter reflection

public class SomeClass {
	public function get reflect():Class {
	  return SomeClass;
	}
}

// 100k loops - 9ms
var someclass:Class = object.reflect();

5,489% faster!

I tested some other stuff too, but I won’t put the code up. I did some tests on equalities (testing to see if my object enumerations were faster than string enumerations):

someStringA == someStringB is faster than someObjectA == someObjectB.
someObjectA === someObjectB is faster than someStringA == someStringB.
someObjectA === someObjectB is faster than someStringA === someStringB.
someObjectA !== someObjectB is faster than someObjectA != someObjectB
someStringA !== someStringB is just as fast as someStringA != someStringB

Of course, use these sparingly, readability is king — but if you’re trying to speed yourself up like I am trying to do, then you can squeeze 1-2 ms out of your enter_frame handlers. For games I would recommend the duplicated math functions, since those are used all over the place. Obviously for bitmap handling the POINT is a huge increase, and reduces objects that need to be gc’d. The other stuff might be a little anal, though using the package variable STAGE i love using — as i can now reference the stage in a constructor, rather than having to wait for it to be added to the stage, the added speed is a bonus, as well as not having to listen for Event.ADDED.

That is all.

39 Comments »

  1. Dennis wrote,

    Hey Daniel,
    Nice stuff! Really useful. I added your post to the other links: http://rozengain.com/?postid=35

    Comment on May 1, 2007 @ 11:08 am

  2. Indefinite Articles » Optimizations in ActionScript 3 wrote,

    [...] Daniel Hai provides a bunch of techniques to improve the speed of certain common actions in ActionSc…. None of them were screaming at me to implement forthwith, but they are worth reading and being familiar with in case you’ll need them in the future.  Bookmark on del.icio.us    Filed under: Agile Software Development by — jb @ 12:14 pm [...]

    Pingback on May 2, 2007 @ 5:14 am

  3. Patrick wrote,

    One question: If I use

    private static const POINT:Point = new Point(0,0);

    the constant POINT is holding a reference to the instance of Point. I’m now wondering if I can also actually change a property of this instance (like, .x :) – I’m not changing POINT because I don’t actually change the reference, I’m not changing the whole instance. Is this correct?

    Comment on June 4, 2007 @ 10:54 pm

  4. Daniel Hai wrote,

    If you change the point: POINT.x = 1 — you are actually changing the constant. What is constant is the object, not the properties of the object. The reason for the POINT is for re-use, since it is used a lot in bitmap operations, as well as transformation operations as well. It’d probably be better to just clone the point if you want to re-use it again .. the clone() is probably faster than a new Point(0,0) anyways.

    Comment on June 6, 2007 @ 7:44 am

  5. derek means wrote,

    I ran my own tests on some of these speed techniques. I got different results. Without reposting all of it here I found that storing package functions as constants such as const abs:Function = Math.abs resulted in run times 70-75 percent slower.

    Comment on August 31, 2007 @ 9:36 am

  6. Daniel Hai wrote,

    You are correct. I will update it for it to be correct. It seems as if Flash recognizes the function as not native, and the execution is slower. I was testing the lookup to the function, rather than the execution itself. Thank you for finding that.

    Comment on September 6, 2007 @ 3:58 pm

  7. 雨飞 BLOG » Blog Archive » as3效率优化 wrote,

    [...] More performance tuning in Actionscript 3 [...]

    Pingback on September 19, 2007 @ 8:05 am

  8. Sean wrote,

    // 100k loops: 202ms
    // 100k loops: 22 ms
    // 18% faster

    Wait, what?

    Comment on February 7, 2008 @ 11:28 pm

  9. Seven tips about performance optimization in Actionscript 3 « Game Development Juice wrote,

    [...] Daniel Hai’s Blog: http://www.danielhai.com/blog/?p=55 [...]

    Pingback on February 15, 2008 @ 11:22 am

  10. Confluence: CAR003 - Punto de Venta wrote,

    Buenas Practicas…

    Introduccion. El fin de esta pagina es agrupar todas la Buenas Practicas que fuimos recolectando de distintas fuentes para evitar problemas de performace/memory leaks en aplicaciones Flex/AIR…….

    Trackback on March 24, 2008 @ 7:41 pm

  11. Visual Harmonics wrote,

    New ActionScript Optimisations Page…

    I’ve just put up a page (see bright orange bar along the top, you can’t miss it) containing a amalgamation of all the AS optimisations I’ve come across recently while hunting around for ways to speed up code. I’ll be updating i…

    Trackback on June 22, 2008 @ 12:50 pm

  12. CaioToOn! wrote,

    Hi, Daniel!

    I tried to create my owns packages variables, but always crash on “undefined variable” error… any suggestion?

    CaioToOn!

    Comment on June 27, 2008 @ 12:33 pm

  13. łojotokowe zapalenie wrote,

    // 100k loops: 75ms
    // 100k loops: 8ms
    838% faster

    How can you be more than 100% faster?
    Faster = 1 - (8 / 75) = 89.33%

    But the first example is in fact 937,5% slower than the second.

    Comment on July 9, 2008 @ 5:34 am

  14. Rozengain.com - New Media Development Blog » Blog Archive » Some ActionScript 3.0 Optimizations wrote,

    [...] More performance tuning in Actionscript 3 [...]

    Pingback on August 11, 2008 @ 3:04 am

  15. Optimizations links | JADBOX: Web Application Musings wrote,

    [...] More performance tuning in Actionscript 3 [...]

    Pingback on August 11, 2008 @ 6:12 am

  16. Confluence: Rich Internet Apps wrote,

    Buenas Practicas…

    Introduccion El fin de esta pagina es agrupar todas la Buenas Practicas que fuimos recolectando de distintas fuentes para evitar problemas de performace/memory leaks en aplicaciones Flex/AIR…….

    Trackback on August 14, 2008 @ 11:43 am

  17. Paul Mignard » Blog Archive » Giving up elegance for speed - a tale of Flex Builder 3 woes… wrote,

    [...] at this point that I was going to have to cram a hack in somewhere - I took the advice from this post that talked about creating some sort of function that returns the object you want without really [...]

    Pingback on August 28, 2008 @ 8:43 pm

  18. Hunter Loftis wrote,

    @Sean… 18% - what? 2nded.

    Comment on December 11, 2008 @ 5:29 am

  19. Rita wrote,

    SOS! My auto was btoken on ave. Must I call to service or 911?

    Comment on January 17, 2009 @ 3:56 pm

  20. Nelly wrote,

    and what do you think about energo crisis in Russia?

    Comment on January 18, 2009 @ 7:18 am

  21. Olga wrote,

    Where I can to find blogs on this topic??

    Comment on January 20, 2009 @ 3:58 am

  22. Zarema wrote,

    It’s hard to understand..

    Comment on January 20, 2009 @ 2:45 pm

  23. Bot wrote,

    So cool!

    Comment on January 21, 2009 @ 3:20 am

  24. Leyla wrote,

    Oh, it’s true, I know!

    Comment on January 21, 2009 @ 8:10 am

  25. Summer wrote,

    Super! I’ll do similarr post in own blof

    Comment on January 22, 2009 @ 3:32 am

  26. Stephen Calender wrote,

    Great Suggestions, I’ve tested all of these myself and my results concur. If you are interested in more Flash ActionScript 3.0 performance tips check out my article http://www.stephencalenderblog.com/?p=7

    ~Stephen

    Comment on February 7, 2009 @ 9:04 am

  27. sonic fast food wrote,

    Thanks!!! Nice post!

    Comment on October 20, 2009 @ 3:12 pm

  28. SpkingR wrote,

    Very nice article! Never saw that, thanks!

    Comment on October 30, 2009 @ 7:42 pm

  29. Constants and Speed at AlecMcE.com wrote,

    [...] tested package constants on the basis that this blog I came across suggested that I could get a performance saving by using package constants. This does not appear to [...]

    Pingback on November 17, 2009 @ 4:46 am

  30. Любовник wrote,

    О! Спасибо автор, очень признателен!

    Comment on November 17, 2009 @ 1:03 pm

  31. CixCineenvike wrote,

    Выяснить пол ребенка

    Comment on January 23, 2010 @ 10:53 am

  32. Amoxicillin to treat acne. wrote,

    Amoxicillin and clavulanate potassium indications….

    Can i have a beer if i m taking amoxicillin. Amoxicillin and strep b. Correct dosage amoxicillin 500 mg. Buy amoxicillin without prescription….

    Trackback on January 28, 2010 @ 11:29 pm

  33. Газенваген wrote,

    Ну просто каждый пост у вас шедевр, просто дух захватывает в каждой статье, вам бы ещё пару блогов открыть не мешало!

    Comment on February 10, 2010 @ 3:05 am

  34. ループ関連の処理速度の高速化 « initt.blog() wrote,

    [...] http://www.danielhai.com/blog/?p=55 [...]

    Pingback on February 11, 2010 @ 9:02 am

  35. Oleg.Dunaev wrote,

    Да откуда вы все такие умные сдесь взялись. Нет смысловой информации вообще.

    Comment on February 27, 2010 @ 3:47 pm

  36. christian louboutin wrote,

    it is interesting and informative article. This has been very helpful understanding a lot

    of things. I’m sure a lot of other people will agree with me.

    Comment on March 6, 2010 @ 12:14 am

  37. смотреть онлайн интерны wrote,

    сериал интерны

    Comment on March 28, 2010 @ 4:15 am

  38. Free Flash Files wrote,

    Performance is everything especialy in flash

    If you have any flash files you would like to share, come upload them to Free Flash Files

    Comment on April 29, 2010 @ 2:26 am

  39. registry cleaner review wrote,

    i search your blog form bing,great post,thanks for share

    Comment on May 19, 2010 @ 6:01 am

Leave a comment

RSS feed for comments on this post. TrackBack URI