Home  >  

Round up of ActionScript 3.0 and Flex optimization techniques and practices

Author photo
April 23, 2009 | | Comments (76)
AddThis Social Bookmark Button

A homework assignment I was recently given for a Java programming class involved a competition to see who could create the most optimized implementation of an interface which was provided by the instructor. It was a challenging and very fun assignment that I think the whole class enjoyed. I didn’t win the competition but still came out a winner because of my heightened interest in application optimization and performance tuning that I gained.

I’m personally a pretty big fan of coding standards and have been ribbed by many developers over some of the longer method, variable and class names that I sometimes choose. I've always leaned toward the side of programming that employs standards and frameworks . Rather than spending a ton of time digging around in compiler specs and messing with GC (Garbage Collection) for reasons of performance, tuning and optimization. I was leaving this to the seasoned programmers creating the standards and frameworks I use.

This isn’t to say I’ve never paid attention to performance and I enjoy building slow applications. It’s almost like two different worlds; the optimization world and the standards world. They don’t always agree with each other. There can sometimes be a trade off for performance over readability and organization or vice-versa. This article is meant to stand next to the Flex Best Practices articles that I authored.

While creating my concrete implementation for the homework assignment I discovered a powerful profiling engine in NetBeans. The NetBeans profiling engine helped me understand some of the memory usage and consumption of each property, method call and object instantiation in my program. This profiler in NetBeans is very similar to the one found in Flex Builder. Both are very powerful and very useful. I've been exploring the Flex Profiler in greater detail lately as well and using it to eradicate memory leaks for a real world application I’ve been refactoring to best practices lately.

The Java optimization homework has increased my interest in optimization and profiling for ActionScript 3.0 and Flex development. I've been piecing together ActionScript optimization techniques and practices from around the web for a couple years now. Some of these techniques are in opposition to what the standards dictate but most of software development is this way. You have to learn when to use some techniques and when to leave some out.

Here is a round up of ActionScript 3.0 and Flex optimization techniques and practices. I’ve scoured the web for and filtered practices and techniques that can be adopted into your application development process.

1. Avoid the new operator when creating Arrays

 
var a = []; 

NOT:

 
var a = new Array(); 

2. Arrays are expensive to create, do so conservatively

 
var vanityCollection01 : Array = new Array(); 
var vanityCollection02 : Array = new Array(); 
var vanityCollection03 : Array = new Array(); 
var vanityCollection04 : Array = new Array(); 

3. Fastest way to copy an array:

 
var copy : Array = sourceArray.concat();   

4. Setting values in Arrays is slow

 
employees.push( employee ); 
employees[2] = employee; 

5. Getting values from Arrays is twice as fast as setting

 
var employee : Employee = employees[2]; 

6. Use static for properties methods that do not require an object instance

 
StringUtils.trim( "text with space at end " ); 
Class definition: 
package 
{ 
     public final class StringUtils 
         { 
          public static function trim( s : String ) : String 
          { 
               var trimmed : String; 
               // implementation... 
               return trimmed; 
           } 
      } 
} 

7. Use const for properties that will never change throughout the lifecycle of the application

 
public const APPLICATION_PUBLISHER : String = "Company, Inc."; 

8. Use final when no subclasses need to be created of a class

 
public final class StringUtils 

9. Length of method/variable names doesn't matter in ActionScript 3.0 (true in other langs)

 
someCrazyLongMethodNameDoesntReallyImpactPerformanceTooMuch(); 

10. One line assignments DO NOT buy any performance (true in other langs)

 
var i=0; j=10; k=200; 

11. No difference in memory usage between an if statement and a switch statement

 
if ( condition ) 
{ 
     // handle condition 
} 

IDENTICAL MEMORY USAGE:

 
switch ( condition ) 
{ 
     case "A": 
         // logic to handle case A 
     break; 
      
     case "B": 
         // logic to handle case B  
     break; 
} 

12. Rank your if statements in order of comparisons most likely to be true

 
if ( conditionThatHappensAlot ) 
{ 
     // logic to handle frequently met condition 
} 
else if ( conditionThatHappensSomtimes )  
{ 
     // handle the case that happens occaisonally 
} 
else  
{ 
     // handle the case that doesn’t happen that often 
} 

13. AVM promotes int to Number during calculations inside loops (VM has been changing, from 9 to 10, so int, uint and number conversions aren't as slow as they used to be.)

14. Resolve issues of promotion, unknown, or incorrect object types

15. Use uint sparingly, it can be slow (VM has been changing, from 9 to 10, so int, uint and number conversions aren't as slow as they used to be.)

 
var footerHex : uint = 0x00ccff; 

16. Use integers for iterations

 
(var i: int = 0; i < n; i++) NOT for (var i: Number = 0; i < n; i++) 

17. Don't use int with decimals

 
var decimal : Number  = 14.654; 

NOT:

 
var decimal : int  = 14.654; 

18. Multiply vs. Divide: instead of 5000/1000 use: 5000*0.001

19. Locally store function values in for and while statements instead of repeatedly accessing them

 
for (..){ a * 180 / Math.PI; }  
declare: toRadians = a*180/Math.PI; outside of the loop 

20. 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++){ } 

21. Use RegEx for validation, use string methods for searching

 
// postal code validation example using regular expressions 
private var regEx:RegExp = /^[A-Z][0-9][A-Z] [0-9][A-Z][0-9]$/i; 
private function validatePostal( event : Event ) : void 
{ 
     if( regEx.test( zipTextInput.text ) ) 
     { 
          // handle invalid input case 
      } 
} 
 
// search a string using String methods 
var string : String = "Search me"; 
var searchIndex : int = string.indexOf( "me" ); 
var search : String = string.substring( searchIndex, searchIndex + 2 ); 

22. Reuse objects to maintain a “memory plateau” DisplayObjects, URLLoader objects

23. Follow the Flex component model:

 
createChildren(); 
commitProperties(); 
updateDisplayList(); 

24. Only use Datagrids as a last resort (make sure you can’t implement in a regular List first)

25. Avoid Repeaters for scrollable data

26. Avoid the setStyle() method (One of the most expensive calls in the Flex framework)

27. Using too many containers dramatically reduces the performance of your application

 
<mx:Panel> 
    <mx:VBox> 
        <mx:HBox> 
            <mx:Label text="Label 1" /> 
             <mx:VBox> 
                  <mx:Label text="Label 2" />  
              </mx:VBox> 
              <mx:HBox> 
                  <mx:Label text="Label 3" /> 
                  <mx:VBox> 
                      <mx:Label text="Label 4" /> 
                  </mx:VBox> 
              </mx:HBox> 
          </mx:HBox> 
      </mx:VBox> 
</mx:Panel> 

28. You do not need to always use a container tag as the top-level tag of components Totally valid component, no top level container needed:

 
<mx:Image xmlns:mx="http://www.adobe.com/2006/mxml"  
     source="avatar.jpg" width="200" height="200" /> 

29. Remove unnecessary container wrappers to reduce container nesting

30. Avoid: The VBox container inside an tag, (eliminates redundancy)

 
<mx:Panel> 
    <mx:Label text="Label 1" /> 
    <mx:Label text="Label 2" /> 
</mx:Panel> 
<mx:Panel> 
     <mx:VBox> 
        <mx:Label text="Label 1" /> 
        <mx:Label text="Label 2" /> 
    </mx:VBox> 
</mx:Panel> 

31. Avoid: VBox container inside an mx:Application tag, (eliminates redundancy)

 
<?xml version="1.0" encoding="utf-8"?> 
<mx:Application xmlns:mx=http://www.adobe.com/2006/mxml> 
    <mx:Label text="Label 1" /> 
    <mx:Label text="Label 2" /> 
</mx:Application> 

NOT:

 
<?xml version="1.0" encoding="utf-8"?> 
<mx:Application xmlns:mx=http://www.adobe.com/2006/mxml> 
    <mx:VBox> 
        <mx:Label text="Label 1" /> 
        <mx:Label text="Label 2" /> 
    </mx:VBox> 
</mx:Application> 
 

32. Set the recycleChildren property to true to improve a Repeater object's performance (re-uses previously created children instead of creating new ones)

 
<mx:Script> 
    <![CDATA[ 
        [Bindable] 
        public var repeaterData : Array = ["data 1", "data 2"]; 
    ]]> 
</mx:Script> 
 
<mx:Repeater id="repeater" dataProvider="{repeaterData}">  
    <mx:Label text="data item: {repeater.currentItem}"/> 
</mx:Repeater> 

33. Keep framerate set at 60 fps or lower

 
<?xml version="1.0" encoding="utf-8"?> 
<mx:Application xmlns:mx=http://www.adobe.com/2006/mxml  
    frameRate="45"> 
</mx:Application> 

34. Avoid multiple display manipulations per frame

35. Code against ENTER_FRAME events instead of Timer events

 
public function onEnterFrame( event : Event ) : void 
{ 
} 
private function init() : void 
{ 
     addEventListener( Event.ENTER_FRAME, onEnterFrame ); 
} 

NOT:

 
public function onTimerTick( event : Event ) : void 
{ 
} 
private function init() : void 
{ 
     var timer : Timer = new Timer(); 
     timer.start(); 
     timer.addEventListener( TimerEvent.TIMER, onTimerTick ); 
} 

36. To defer object creation over multiple frames use:

 
<mx:Container creationPolicy="queued"/>  

37. Alpha = 0 is not the same as visible = false (Objects marked invisible are passed over)

 
loginButton.visible = false; 

NOT:

 
loginButton.alpha = 0; 

References:

Sean Christmann: Optimizing Adobe AIR for Code Execution, Memory, and Rendering
http://www.craftymind.com/2008/11/20/max-2008-session-material/

Dennis Ippel: Some ActionScript 3.0 Optimizations
http://www.rozengain.com/blog/2007/05/01/some-actionscript-30-optimizations/

Shane McCartney: Tips on how to write efficient AS3
http://www.lostinactionscript.com/blog/index.php/2008/09/28/tips-on-how-to-write-efficient-as3/

Flex Application Performance: Tips and Techniques for Improving Client Application Performance
http://www.adobe.com/devnet/flex/articles/client_perf.html

Stephen Calender: ActionScript 3.0 Benchmarking
http://www.stephencalenderblog.com/?p=7

Grant Skinner: Types in AS3: ints not so fast, uints slow!
http://www.gskinner.com/blog/archives/2006/06/types_in_as3_in.html

Grant Skinner: Resource management strategies in Flash Player 9
http://www.adobe.com/devnet/flashplayer/articles/resource_management.html

Gary Grossman: ActionScript 3.0 and AVM2 Performance Tuning
http://www.onflex.org/ACDS/AS3TuningInsideAVM2JIT.pdf

Fastest way to copy an array
http://agit8.turbulent.ca/bwp/2008/08/04/flash-as3-optimization-fastest-way-to-copy-an-array/

Andre Michelle: AS3 optimations & suggestions
http://blog.andre-michelle.com/2005/as3-optimations-suggestions/

Package-level function closures in ActionScript
http://www.ericfeminella.com/blog/2008/05/06/package-level-function-closures-in-actionscript/

ActionScript 3 optimization techniques
http://blog.joa-ebert.com/2008/04/26/actionscript-3-optimization-techniques/

AS3 Performance Tester
http://businessintelligence.me/projects/performance_tester/performanceTester.html

Read more from Sean Moore. Sean Moore's Atom feed seantheflexguy on Twitter

Comments

76 Comments

John Lindquist said:
Jesse Freeman said:

This is excellent, I must read for any ActionScript developer!

Paw Suddergaard said:

Great list!

I think you have the wrong order in no. 25.

var len : int = myArray.lengh;
for (var i=0;i

Is FASTER THAN

for (var i=0;i

Mike Henderson said:

Great article, Sean! I'm definitely guilty of a few of those. I always enjoy reading these sort of best practice/code optimization articles.

Mike Henderson said:

Great article, Sean! I'm definitely guilty of a few of those. I always enjoy reading these sort of best practice/code optimization articles.

John Dalziel said:

Great list Sean! One quick correction through. I think the examples for no.25 have been listed the wrong way around:

var len : int = myArray.lengh;
for (var i=0;...

will be faster than

for (var i=0;...

Ben Beaumont said:

Grant Skinner has just released a AS3 performance testing harness: http://www.gskinner.com/blog/archives/2009/04/as3_performance.html

Ben Beaumont said:

Grant Skinner has just released a AS3 performance testing harness: http://www.gskinner.com/blog/archives/2009/04/as3_performance.html

Cesare said:

Incredibly valuable suggestions. Thanks Sean for sharing!

I was wondering about #33 ... any alternative to setStyle() ?

Jerry Ela said:

Premature optimization is the root of all evil - Donald Knuth

While most of your suggestions are fine for general use, some of them can make for difficult to maintain code. That can be an acceptable trade off if you are doing it to address a real performance issue, but not where the microsecond you save won't make any difference.

Particularly #s 45, 46 and 47 break encapsulation and should not be done as general practices. Putting all your code inline instead of in methods is likely to hurt performance as it will significantly increase the size of the compiled code, while it could help if limited to those places where performance is a real issue.

Also, I think you need to add a cred property to the first example in 47 and a userName property to the second.

Tyler Egeto said:

Good list!

Couple of notes, delete does not free memory, but can be used on dynamic objects to remove references, enabling them for garbage collection, assuming there are no other references to them. For a non dynamic object simply set them to null.

For Cast() vs. as, these two methods have an important difference, "as" type checks the object and will return null if the statement is false, while a straight Cast() with through an error. Also I thought "as" was actually the slower of the two, because of the type check?

Great list again, thanks for sharing!

Maxim Porges said:

Are you absolutely sure all these tips are (a) still valid in the AS3 language spec and (b) actually faster?

In #27, I don't think the "delete" operator works the way you suggested in AS3. From the AS3 docs: "Also new to ActionScript 3 is the behavior of the delete keyword. The delete keyword is used to delete variables from an object. Variables defined with var, however, cannot be deleted in ActionScript 3. Only dynamic variables defined within dynamic objects can be deleted with delete. For other variables, the equivalent of deleting would be to set those variables to have a value of null."

#23 strikes me as ludicrous since Math.as is compiled against a native C implementation in Tamarin. I don't have time to test this but I would be absolutely floored if a self-built rounding function implemented in AS3 and running in the AVM as bytecode ran faster than a native call.

For #16, I compiled the following function in a class using asc and compared the opcodes.

First attempt with explicit cast to int: 49 opcodes


public function loops() : void
{
for (var i : int = 0; i {
trace(i += int(5));
}
}

function loops():void /* disp_id 0*/
{
// local_count=3 max_scope=1 max_stack=4 code_len=50
0 getlocal0
1 pushscope
2 pushbyte 0
4 convert_i
5 setlocal1
6 jump L1


L2:
10 label
11 findpropstrict trace
13 getlocal1
14 findpropstrict int
16 pushbyte 5
18 callproperty int (1)
21 add
22 dup
23 setlocal2
24 convert_i
25 setlocal1
26 getlocal2
27 kill 2
29 callproperty trace (1)
32 pop
33 getlocal1
34 increment_i
35 convert_i
36 setlocal1

L1:
37 getlocal1
38 findpropstrict int
40 pushbyte 10
42 callproperty int (1)
45 iflt L2

49 returnvoid
}

Second attempt with no cast to int: 39 opcodes


public function loops() : void
{
for (var i : int = 0; i {
trace(i += 5);
}
}

function loops():void /* disp_id 0*/
{
// local_count=3 max_scope=1 max_stack=3 code_len=40
0 getlocal0
1 pushscope
2 pushbyte 0
4 convert_i
5 setlocal1
6 jump L1


L2:
10 label
11 findpropstrict trace
13 getlocal1
14 pushbyte 5
16 add
17 dup
18 setlocal2
19 convert_i
20 setlocal1
21 getlocal2
22 kill 2
24 callproperty trace (1)
27 pop
28 getlocal1
29 increment_i
30 convert_i
31 setlocal1

L1:
32 getlocal1
33 pushbyte 10
35 iflt L2

39 returnvoid
}

The added casts throw in more findpropstrict and callproperty opcodes to perform the casts, resulting in more opcodes to be executed. Also, there were no explicit casts from Number to int in the second attempt, so unless the AVM goes out of its way to add them, I doubt they occur. Again, I have not profiled this to see how the AVM reacts to the changes but I would be surprised if more opcodes to execute resulted in increased performance.

- max

Brandon Ellis said:

Hey Sean,
Great list. Some really useful information in there. :)

mrm said:

Regarding #18 & #19: http://twitter.com/gskinner/status/1544926568

In #48 you said "obj as Class" is faster than Class(obj) then you use Vector3D(array[i]) in #50 which also contradicts #20

#26 is redundant if you use addEventListener(Event.TYPE, someFunction, false, 0, **true**);

#27 is wrong, as another commenter pointed out

Aki Lee said:

After more than 20 years of programming experience, I just can say that your post is true only for banchmarking, not for development.
If you are a developer (or even a software architect), you will not use these approaches in most cases. Only for hacks and workarounds. :-)

Keep up the good work!

Sean Moore said:

Thanks a lot for all of the great feedback guys. I agree that some of these are 'hacky'. As mentioned I generally try to strive for clear, understandable code vs tricks. I wanted to gather all of the optimization info from around the web into one article. I'll make the edits mentioned and really appreciate the feedback. I think it's helping to make the article a much stronger source of info. Also please note the two articles I wrote for Adobe on best practices.

Mark Lapasa said:

I am 5 years shy of flash programming experience, I can say that if your target audience provides you with feedback that your application is not as fast as they would expect, then one must do everything possible. I am a developer that would be more than happy to exercise these tips. In fact, I already have applied some of these tips since I first learned of them from Flex conferences I've attended in the past.

The Flash Player VM, as I've learned over the years, is a beast of it's own kind. What works well in another language may not necessarily work well in AVM. It is it's own animal with it's own quirks. Try...catch() is one such example which I've been told is very expensive where in Java it's not an issue.

Gwenn said:

Hi !
I saw on another blog to not use "const" but var instead. You say the opposite. What's the true ?
Then I agree with Paw Suddergaard about the array length.
Thanks.

Pedro Abrantes said:

@Gwenn:

Well, since const variables don't change, the compiler can replace all const accesses by the value itself, generating an optimized version of the code. In this particular case, I do not think using var would boost performance.

zguillez said:

wow! great list! thnks ;)

Joseph said:

This is Extremely Useful!! Supper Post!!

Ryan O'Connell said:

Whoa! There are alot of incorrect things here, I don't know where to begin. First of all, don't believe eveything you read in a AS3 blogs. Second of all, the VM has been changing, from 9 to 10, so FYI int / uint / number conversions aren't as slow as they used to be.

The biggest fallacy in this list is this one:

23. Calculate things like floor and round yourself vs. calling Math library

Why do you think an actionscript written floor / round routine will be more efficient than the one written in c++? Did you mean to write DON'T calculate floor/round in actionscript? What was your reference on this?

BTW I work at Adobe, on actionscript projects.

Tyler Egeto said:

In regards to Math.floor/round, those static methods calls are pretty slow, faster alternatives are floor -> int(myNumber), round -> int(myNumber + 0.5).

Sean Moore said:

Thanks for the continued feedback on the article. All of the references are listed at the bottom. I pulled all the items in the list from the various references and added code samples that I thought would help illustrate the tips. Sorry for any incorrect tips/advice. All of the sources seemed pretty valid. I am going to update the items that people have supplied the great feedback on.

Jidolstar said:

Wow! Very Good Article.

Jethro said:

Well loads of inaccuracy, bad practice and contradiction.
I wont repeat previous posters but one more edit needed...

#6 and #49 seem to contradict each other.

Jethro said:

One more...

#51 would only make any sense for null object exception.

Blackiz said:

Great!!!

am said:

Jethro, @6 says to avoid new when creating a object, @49 avoid Object insted use CustomObject. Has far as I understands that gives you 3 possibilities:

.1
var obj:CustomObject = {jethro:'i like turtles'};

.2
var obj:CustomObject = new CustomObject ();
obj.jethro = 'i like turtles';

.3
var obj:Object = new Object ();
obj.jethro = 'i like turtles';

I'm no good with this at all, but seam to have some logic... maybe i'm not getting your point...

Kristofer said:

Interesting article! If nothing else, this is obviously a great place to find out which performance myths that really are valid. :-)

But I truly agree on Jerry Ela's reminder:"Premature optimization is the root of all evil"...

Matheus said:

Great post, thanks. But here are some comments:
#4: The ideal is t use "push" instead of setting the new index value?
#6: Doesn't this contradicts the number #49?
#10: You said to create package level functions, but you also said NOT to the 3rd example where you do it.
#11: Could you talk a bit more about that? It's not very clear.
#23: Are you saying that it's better to create our own Math library instead of using the built in one?

thibaud said:

#25: is in the wrong order.

Cliff Meyers said:

The sheer number of contradictions, inaccuracies and crazy suggestions (don't use Math.round, really?) is staggering. Please take this article down until you validate what optimizations are actually true.

Prashant Jain said:

Sean,
Great article and eye opener.

It is missing one thing, why is one better or optimized over the other. If that information was there, I would have learnt a lot more.

Hope you can put another article explaining that. Just one line for each would do.

Thanks
Prashant

Jethro said:

@am

> .1
> var obj:CustomObject = {jethro:'i like turtles'};

is not valid actionscript.

My point is the two points (6 and 49) contradict each other.

#49 recommends creating custom object (which is good practice anyway), but you have to use the new operator, which in turn contradicts #6!

I think what Sean is trying to get at is...

Use custom object (type) rather than untyped Object. If however you must use plain untyped Object, create it with braces rather than new Object().

However, I think the lesson to learn over this collection of 'hints' is a) dont read every blog post as gospal and b) do your own tests and optimize when needed and c) program to good practice first, optimize later if need be.

matt said:

I think it would make more sense to the reader if you sad Good vs. Bad instead of using NOT.

Sean Moore said:

Hey All,

Thanks so much for all of the great feedback. All of the offending techniques should now be eradicated from the list. Sorry for any confusion.

Sean

Isaac said:

Wow, these are some EXCELLENT techniques. Thank you for posting them. My only question is about uint. I was always under the assumption uint was faster than int because it's an unsigned integer. Also, I thought an integer was faster than number because it deals with whole numbers. My question is: How can a variable that handles real and non real values be more efficient than a variable that handles only real whole numbers?

Paul Robertson said:

I won't try to use rule numbers, since it seems that the numbers have changed based on comments that refer to numbers that no longer exist =)

I will say that regarding Array use, in Flash Player 10+/AIR 1.5+ for iteration and retrieving values it's faster to use Vector instead of Array if you can (if all the items have the same type and you don't need a sparse array). If the items aren't the same type, you could use Vector. (which I thought was a programmer joke the first time I saw it) -- in that case I'd predict that iterating would be faster although retrieving values would probably be the same as with Array. Note however that for some operations (specifically splice(), and perhaps others that rearrange elements) benchmarks show that they run 10% slower for Vector than Array.

Also, based on my own performance tests, I found instance methods to run notably faster than identical static methods (not sure why, that's just what I found). I was testing a particular set of methods of course (XML handling if I recall) and my testing was ~3 years ago, but I choose to avoid static methods in most cases and use a singleton instead.

The Vector stuff is in the documentation, and since I wrote that documentation I happen to know that it comes straight from the Flash Player engineers. For the other one, as I mentioned, my only authority is my own performance benchmarks.

Paul Robertson
Adobe AIR/Flash Player/ActionScript documentation team

auzn said:

copy an array,sometimes "slice" is faster than "concat" :)

undersound said:

And what can we develop to have a proper discussion platform instead of lurking around in the comments. I find this information very valuable but some (read: most) the time the information in the comments is even better.

Again, thanks for sharing this ! Love the flash community

undersound said:

And how can we come up with a medium to have a proper discussion instead of lurking around in the comments. I love blogs, but i always find it a bit annoying to look at the discussions in the comments although they are most of the time very good and valuable. I do find it a bit annoying........ah whatever......great post !!

Again, thanks for sharing this ! Love the flash community

GD said:

Great article, Thanks

polyGeek said:

Thanks for the post Sean. One thing I've learned is that if you want to solicit some brutal comments then just write about code optimization. :)

This reminds me that I really need to embrace Vectors instead of Arrays in my projects aimed at FP10. I really can't remember the last time I created an array that had mixed types.

That sucks about the Timer being less efficient than the EnterFrame. But I'm going to have to stick with Timer for just about all me interval based code because EnterFrame is too constricting.

polyGeek said:

Thanks for the post Sean. One thing I've learned is that if you want to solicit some brutal comments then just write about code optimization. :)

This reminds me that I really need to embrace Vectors instead of Arrays in my projects aimed at FP10. I really can't remember the last time I created an array that had mixed types.

That sucks about the Timer being less efficient than the EnterFrame. But I'm going to have to stick with Timer for just about all me interval based code because EnterFrame is too constricting.

polyGeek said:

Thanks for the post Sean. One thing I've learned is that if you want to solicit some brutal comments then just write about code optimization. :)

This reminds me that I really need to embrace Vectors instead of Arrays in my projects aimed at FP10. I really can't remember the last time I created an array that had mixed types.

That sucks about the Timer being less efficient than the EnterFrame. But I'm going to have to stick with Timer for just about all me interval based code because EnterFrame is too constricting.

Ryan Sadwick said:

Great article and comments. The discussions here are always informative!

Ryan Sadwick said:

Great article and comments. The discussions here are always informative!

Justin Haygood said:

Another optimization:

Opening a local SharedObject channel takes about 100ms. If you can open it only once in your application, you can see a drastic increase in performance in code that uses it

shaman4d said:

The list has many old information. Also:
1) static methods more time expensive then object methods.
2) use while... loop instead for.... because the first most quickly

var i:int=a.length;
while(i-->0)
{
... do what you want....
}

3) "Length of method/variable names doesn't matter in ActionScript 3.0" - is not so - big-named-variable process more slow
4) There is difference among "if" and "switch" - the first one is faster
5) "const" declaring and calling more slow then "var"

shaman4d said:

The list has many old information. Also:
1) static methods more time expensive then object methods.
2) use while... loop instead for.... because the first most quickly

var i:int=someArray.length;
while(i-->0)
{
... do what you want....
}

3) "Length of method/variable names doesn't matter in ActionScript 3.0" - is not so - big-named-variable process more slow
4) There is difference among "if" and "switch" - the first one is faster
5) "const" declaring and calling more slow then "var"

JoeB said:

These are great best practices, however I wish it was more specific about why certain techniques were better than others, and a sense of the memory cost differences between good and bad practices.

Manfred Karrer said:

Thanks for the great article!
I would like to add one about databinding:
databinding with BindingUtils is 100% faster then in mxml...
you can find more details under: http://www.screenshot.at/blog/2009/04/18/databinding-under-the-hood-part-1-performance/

Rick said:

Can someone clarify these 2?

13. AVM promotes int to Number during calculations inside loops (VM has been changing, from 9 to 10, so int, uint and number conversions aren't as slow as they used to be.)

16. Use integers for iterations


If AVM promotes int to number during a loop, why would you use integers for interations?

Neil Glenister said:

Great article!

On Point 35 states that we should be using ENTER_FRAME events rather than Timer but it's doesn't say why :s.

This is exactly the opposite to what Adobe recommend which is interesting...Can you let me/us know why we should be using ENTER_FRAME? :)

Cheers

Neil

medyum said:

The list has many old information. Also:
1) static methods more time expensive then object methods.
2) use while... loop instead for.... because the first most quickly

var i:int=someArray.length;
while(i-->0)
{
... do what you want....
}

3) "Length of method/variable names doesn't matter in ActionScript 3.0" - is not so - big-named-variable process more slow
4) There is difference among "if" and "switch" - the first one is faster
5) "const" declaring and calling more slow then "var"

Aloe Vera Blogger said:

I like one of your picture. Can I use one of them

Lee said:

all that you point is 200% right you always always always optimize at the end, and only if you know what you re doing and if you really really need it optimization list lure people by making them think that if they apply every single point of the list they will then be good developers because they wrote very optimized code domain names, and this is uterly wrong kind of the same thing happen when some dev discover design patterns and try to shoe horn every single one of them in their code

Helen Hunt said:

Thanks for this awesome tip. I have found quite a few of them very useful not only on Flex applications, but on Java as well.

Thanks again for sharing.

B Matuk said:

Thanks for these great tips. Nice work.
I can only see items #1 to #37.
I don't see a link for page 2 or anything.
Where are the remaining items?

Jenny said:

Holy cow - this is awesome. If only I could have wrote it...

Justin said:

Very useful man! Much appreciated.

-j

william said:

A homework assignment I was recently given for a Java programming class involved a competition to see who could create the most optimized implementation of an interface which was provided by the instructor. It was a challenging and very fun assignment that I think the whole class enjoyed. I didn’t win the competition but still came out a winner because of my heightened interest in application optimization and performance tuning that I gained.

I’m personally a pretty big fan of coding standards and have been ribbed by many developers over some of the longer method, variable and class names that I sometimes choose debt consolidation. I’ve always leaned toward the side of programming that employs standards and frameworks . Rather than spending a ton of time digging around in compiler specs and messing with GC (Garbage Collection) for reasons of performance, tuning and optimization. I was leaving this to the seasoned programmers creating the standards and frameworks I use.

Mikey said:

Its pretty much effort putting task to get some thing out of the box, i did participate in couple of web and seo based coding projects, but honestly i failed to get some good position, due to a lot high rated competitor or simply i was not up to the mark. One of my friend is working in java for a website hosting company and he is wins a competition in NC. Well your effort seems very decent and thanks a lot for sharing.

flashmoto cms said:

awesome article.
btw using BindingUtils is much faster then in mxml.

misty said:

To win any sort of field there are some requirements like in canadian web hosting we need the hosting tricks to rank sites.Well i appreciate your efforts that put you in peak.I have recently participated in competition of php coding for budget web hosting server.I hope will win let see what will be happen.

Vilambara said:

Excellent article.. Very informative.Refreshes me about yui application link building

Ian Fillion-de Kiewit said:

Thanks for the article! Saves me from a bunch of testing

I got something for your tip #1

turns out that if you have an array with a very low amount of values (7 seems to be the highest possible amount of values for this to work)

you can use a loop (while seems to be the fastest one) to pop() out all the values of your array instead of doing array = []

NOTE: shift() out values of the array is slower than anything else

EXAMPLES:


Array of 2 values:

following takes ~25 ms to run


for(var i:int = 0; i < 50000; i++){
arrTest = [];
for(var j:int = 0; j < 2; j++){
arrTest.push(j);
}
}

following takes ~ 17 ms to run


for(var i:int = 0; i < 50000; i++){
while(arrTest.length > 0){
arrTest.pop();
}
for(var j:int = 0; j < 2; j++){
arrTest.push(j);
}
}

ok, just for fun...lets try shift()

following takes ~30 ms to run


for(var i:int = 0; i < 50000; i++){
while(arrTest.length > 0){
arrTest.shift();
}
for(var j:int = 0; j < 2; j++){
arrTest.push(j);
}
}

Array of 7 values:

following takes ~56 ms to run


for(var i:int = 0; i < 50000; i++){
arrTest = [];
for(var j:int = 0; j < 7; j++){
arrTest.push(j);
}
}

following takes ~ 55 ms to run


for(var i:int = 0; i < 50000; i++){
while(arrTest.length > 0){
arrTest.pop();
}
for(var j:int = 0; j < 7 j++){
arrTest.push(j);
}
}


Array of 20 values:

following takes ~118 ms to run


for(var i:int = 0; i < 50000; i++){
arrTest = [];
for(var j:int = 0; j < 20; j++){
arrTest.push(j);
}
}

following takes ~ 155 ms to run


for(var i:int = 0; i < 50000; i++){
while(arrTest.length > 0){
arrTest.pop();
}
for(var j:int = 0; j < 20 j++){
arrTest.push(j);
}
}

hope that can be useful to someone

Sandio said:

I downloaded Netbeans awhile ago but wouldn't have survived it without the foum and developer code they make available to users. Because it's free (and powerful), it was a great way to start working with PHP scripts. That and a book on Apache and web development - and another month spent reading it - and I was off and running. Nothing quite so complicated yet but if I stop snoring and get back to it, I could actually finish the rest of the site I started putting together.

Live the overview of the homework exercise. Actually, in class or not, if you want to learn then doing similar exercises on your own can be rewarding.

James Bradley said:

And when you're ready to wake up, you're going to wake up, and if you're not ready you're going to stay pretending that you're just a 'poor little me. But the whole game that our vistaprint coupon culture is playing is that nothing really happens unless it's in the newspaper. refore everybody feels unhappy and miserable.

Derek said:

Premature optimization is the root of all evil - Donald Knuth

While most of your suggestions are fine for general use, some of them can make for difficult to maintain code. That can be an acceptable trade off if you are doing it to address a real performance issue, but not where the microsecond you save won't make any difference.

Particularly #s 45, 46 and 47 break encapsulation and should not be done as general practices. Putting all your code inline instead of in methods is likely to hurt performance as it will significantly increase the size of the compiled code, while it could help if limited to those places where performance is a real issue.

Also, I think you need to add a cred property to the first example in 47 and a userName property to the second.

syeddiwan said:

this is great article, i have one doubt for setStyle methode in flex frame work,
i can load the css file at run time to module using styleManger, but my question is if we are using one module instance mean so issue, At the same i want to use difference css file to each module instance,here only i am struggle because styleManager is single ton, it's taking only last style definition, For this case we loop through the display object and using setStyle method to apply corresponding style to that displayObject...
I read lot of Flex performance article ,they recommend to avoid setStyle method ,For this case any other alternative way is there,




shb said:

I’m also a pretty big fan of coding standards and have been ribbed by many developers over some of the longer method, variable and class names that I sometimes choose. Thank you very much for sharing!

Joseph, Senior Developer at Bet365 and General Manager of Campionatul Mondial de Fotbal 2010

Jeff Deutsch said:

Thanks for this list. Flex is a nightmare for those first getting into it. I'm trying to build a Flex app to automate the online NJ SEO company engine and it's been a serious headache. At least I can avoid the basic issues though!

Leave a comment


Type the characters you see in the picture above.


Tag Cloud

Latest Features

Recommended for You

@InsideRIA on Twitter

Archives

  • Or, visit our complete archive.  

About This Site

Welcome to the premiere community site for all things RIA sponsored by O'Reilly Media and Adobe Systems Incorporated.