AS3 Performance relative to Java, Javascript, AS2
Good article. For most things Java was 3 times faster, but of course nobody really writes for Java applets. Javascript versus Flash is tricker, and as one can see highly browser dependent...huge differences! I'm so glad I'm not working directly on DHTML apps.
http://www.oddhammer.com/actionscriptperformance/set4/
Working in flash is a bit like a cake on a platter. The cake (your swf) can come in all sorts of flavors that you as a cook can make, and is flexible in shapes, but when hitting the platter (the flash player) you lose this customizability, it's there to allow your cake to stand.
When dealing with actionscript, some code is the icing (your classes), some the cake (flash's instrinsic classes), and some is the platter (functions that are actually natively implemented in C). Depending on how many layers of icing and cake one has to get to before hitting platter, can make orders of magnitude difference. The fastest interpretted actionscript is always slower than the native function calls, as in the end everything has to get boiled down to simpler native calls.
There are many features in flash implemented 'natively' (event dispatching, e4X, binary data + AMF) and as such using them when possible over rolling your own classes, as it may be an order of magnitude faster. This is why it's good to spend time just reading through the packages to understand what is possible, prior to writing your own, as there are many portals into the underlying player substrate.
This has implications on architecting applications. Even if the algorithm in has been tweaked for hours, the 'cleanest' solution may ironically perfom worse, because you're only adding layers of cake and icing instead of going lower.. This often happens when porting proven projects from other languages, or keeping application frameworks in synch on a webserver and flash.
FlashDevelop Beta 3.0 hanging? …potential solution.
I had a wierd issue with Flash Develop Beta 3.0.0 Beta 3. When it hung, it would take windows and task manager with it. Admittedly my install of XP is about a year old and likely to start getting bonked.
What I did that seemed to fix it, was uninstall all the java runtimes, repaired the .Net 2.0 framework and uninstall/reinstall .Net 3.0. Then reinstall FlashDevelop. So far it hasn't hung at all.
AS2 to AS3 Conversion Annoyances
After using FDT and MTASC both with strict compilation, I was thinking that converting to AS3 would be straightfoward. Alas.. no.
Some of it is syntax, but frequently in the pursuit of performance or architectural benefits, I had to take advantage of tricks or in the language, and many of these hacks are breaking, or rather even some of the core features no longer work on the AS3 architecture.
Nullable types bye..
For all the type strict typing in AS3, one of the biggest annoyances is the removal of nullable types. This has had profound impacts on migrating code.
what used to be
public function doSomething(var aNum:Number):void{
if(aNum == null){
aNum = DEFAULT_NUM
}
}
Now I have to use  aNum:* which makes it harder to read, and now I have to introduce argument type checking in the method body, quickly adding to the size. Grr. What's silly is you can still create without initializing vars e.g.
var numA:Number;
//sometime later, what is numA before this?
numA = -1;
in addition, var obj:Object = numA is a legal call. So.
I'd be happy if they make a separate nullable type e..g NullableNumber that extends Number and that NullableNumber is itself finalized.
Initialization Â
The intialization into the function signatures is neat and increases readability, but totally flummoxes collections when your defaulting to the length of the array, here again we have to use the wildcard, which defeats type checking during compilation.
For in...GoodbyeÂ
For in was a useful tool to introspect values and interate over collections. Of course since this uses the prototype chain which is slow it's been relagated to only looking at the prototype chain, as most the variables and method have been moved to the fixed class inheritance, many uses of introspection have been broken, all over the place.
Introduction to ActiveFrame, Cogs, Chain, Score, Sketch, fXperience
Intro to StateMachines
![]()
The good news is if your in team development, you've been diagramming them for years, as flowcharts and bubble diagrams. Bubbles are states, arrows are transitions. This is one of the keys to their usefulness in teams. The diagrams can be understood and modified by anybody, and can represent anything from a users interaction with the whole application, a game's AI, or the graphical transitions in a button rollover. Any Animator who has done keyframes and tweens knows has been unwittingly using states and transitions, but what about developers?
Most any application developer is familiar with OOP, and many design patterns like the State Pattern. Some may have heard of the term finite state machine (FSM) with a possible vague understanding of what one is/does, most are probably not familiar with Hierarchical state machines (HSM), which are especially powerful, especially in experience driven, Flash
and AIR content working with asynchorous network requests, and large media upload/downloads, long timeline, all of which have complicated life cycles with asynchronous call/callback.
I started using them in projects after first learning about them in software from Jonathan Kaye. After using a few different versions in a few different projects, and developing my own, I have been on a quest to spread the word ever since. OOP and SM's foundational aspects. They are orthogonal and complimentary, OOP describes the nouns of the system StateMachines's the behavior over time. An example the cat is meowing, cat is the noun, meowing is the current state, and it will change over time.
Intro to Cogs
Cogs is the AS3 library of statemachines, and common patterns that people can extend/plugin similar to how people reuse design patterns, to avoid reinventing the wheel. Just as in Design patterns, there are fundamental patterns, from simple toggleable button, to synchronized media players.
It's named Cogs first after the tiny teeth that compose gears, that when meshing properly make up engines which power most the mechanical world, and secondly Cognition as the meshing of neurons make up the engines of intelligence. Cogs primary use is increasing the intelligence of components, games, game AI, and applications, by several approaches:
Cogs allows you to ask where you are, where you can go, and automate chains of execution between two states. Often event driven components are black box event generators, identical events broadcast at different times mean completely different things (like NetConnection) this is far from simple.
The FSM and HSM are based on Miro Samek's approach of using functions instead of classes to represent states, this very low level implementation has several advantages, one of the first is being less code to understand and write. It also enables behavioral inheritance, similar to. Cogs is different in several ways from Miro's inspiring work in his book. First all possible transitions are supported instead of just the common ones, and are validated by the unit tests..and the testing framework itself being an FSM and supporting Asynchronous testing easily.
Ongoing I'm working on API's for deep history, serialization/deserialization a graphical visualizer, among other things.
ActiveFrame
Cogs is part/foundation of a larger framework named ActiveFrame. Which strives reduce commmon architectural decays, largely by decoupling.
- A message bus enabling event decoupling,
- Java Spring 'Dependency Injection' for Implementor Interface decoupling,
- plus a decoupling of the UI and controller..which can live in completely different swfs, similar to AS2.0's Object registerClass.
It's reasonably small for all these features, allowing it to be used for components, games, game AI or full blown applications.Sketch
is the visual extension of the Cogs, to deal with the View/UI world (e.g. movieclips/timelines, sprites), common layout, and UI/controller decoupling communication. While Sketch can be used whereever Flash can go, it's strong points are design and script heavy projects, in teams that have strong separations between design and scripting... they don't even have to be working on the same file.
Since it's based on Cogs, it's very easy to prototype and if flow diagrams (state diagrams) are used in the IA and Creative phases, it can act as a common language between design, IA, and engineering, as diagrams can easily be translated to code and back, and reworked easily. It supports what I call "introspectable UI's", in that the statemachine can act as the model, and summarize all the active states supported options to generate an appropriate "where can I go from here" UI.
Chain
is the workflow component, it's coordinates dependent parallel and sequential and nested tasks, with asynchrous call/callbacks, providing status along the way. Some uses for this are preloading assets, playlists, unit testing, easing and tweens, build out and tear down of UI's.
Score
is the the parallel timeline orchestration component, similar to a Orchestral score for coordinating multiple instances with a single virtual playhead. Useful for overlapping events. It's similar to an actionscript version of the Flash IDE timeline.
fXperience
is the visual components library. This is based off Cogs/Sketch, components have a wider lifecycle than those built into Flash and Flex., e.g. a button transitioning in, transitioning to up, transitioning to over etc. They support easy and iteratible skinning, so projects can start out simply as a graphic than graduate to more complicated ones as need requires.
Misc
All are a part of the TroyWorks AS3 code library that is MIT licensed on google (but isn't finished/uploaded yet, API isn't stable) There are many other useful utilities, datastructures and components of interest I'll be covering in more detail as they get more fully flushed out and converted to AS3 from AS2, I'm trying to make sure I don't add something already in AS3, and take full advantage of AS3's architecture.
Tools: FDT + Eclipse vrs FlashDevelop
So after another round of flux in my development environment, I resorted to using Eclipse (for coding) AND FlashDevelop (for compiling and quick projects) in tandem (along with SOS for trace debugging). Talk about a lot of desktop space!
This is because FDT+Eclipse, my favorite tool for ActionScript development is still in Beta (still a great code editor!) and in general building requires Ant tasks in Eclipse, which doesn't support the Flex Compiler Shell (huge speed increases), while FlashDevelop is an good editor, but has great compiler support.
About 2 months ago, with significant trepidation. I finally bit the bullet and made the move to AS3. It's been about 2 pretty turbulent months since. Learning the IDE of 2 major tools (Flash CS3, Flex 3.0 beta ), the massive syntax changes, new workflow, starting to get large libraries converted....breaking across the rocks of different paradigms.   Then midway the Flex beta license ran out (30 days is after all reasonable),. It wasn't worth it spending $300-$500 for a license to FlexBuilder 2.0 to keep going.
- I'm going to Max in October, I know 3.0 is out in a few months,
- The code editor is an order of magnitude weaker than FDT, and still quirky enough to make it unuseable at times in the beta, I guess some of my code does some tricky things which causes Flex's language parser to barf.
- I don't plan on using FlexBuilder/Flex on most of my projects...we aren't that data/standard control centric.
This created a window of no reasonable workflow. FlashCS3 does compile AS3 well (I first started having to use it with FlexBuilder 3.0, when running into quirks in it's parser). But the editor isn't much better than a plain text editor, for dealing with large libraries and components. So I started investigating other platforms, Sepy and FlashDevelop...etc. Which is about as motivating as looking at a bicycle after driving an F1,...but admittedly better than walking barefoot or standing still.   I was hoping that in my lack of paying attention that the years since I last reviewed would have some new releases, and while I didn't have time to investigate Sepy, I was pleased with FlashDevelop Beta 3. In a sunday afternoon I got from ground zero to building an AS2, and an AS3 project both using the Flash CS3, and separate the Mxmlc.exe, which nicely prompted me to look for the 'Flex Compiler Shell', which I hadn't heard of before.
http://labs.adobe.com/wiki/index.php/Flex_Compiler_Shell
The compiler shell is designed to startup once then talk with it, telling it to recompile files, typically by getting an id back on the first compile then recompiling. This can amount to huge timesavings. Once installed and incremental compiling is on, It's similar the speed jump to me from using Flash to using MTASC.
YAY!!!!
Incremental compiling has been high on my list of things I've been looking for out of AS3, Java has had this for almost a 8 years, and I grew to depend on it. Java is still way ahead...you can hot fix code running in the VM without restarting...while debugging, even remotely (if allowed)!.
FlashDevelop Beta 3 supports the Flex Compiler Shell without anything special, just drop in and go (very nice!). Sadly for Eclipse/Ant/FDT it won't work well, as the major performance increase is from not having to startup the mxmlc.exe everytime, but ant starts up and closes down as soon as it's finished, and there is no easy way to modify Ant/Eclipse to keep the process/dialog open. But since it's not terribly difficult to have both open, that's what I've done.
The biggest thing that I miss via this is the errors output by the compiler (both the syntax check, and full compile errors) show up in FlashDevelop, which clicking on lets you jump to, when I'd rather do it in Eclipse. Both tools are smart to watch for file changes, so it's possible to edit in both places. If a bit more UI to wrangle than idea;
Performance: Strict equality === versus compare by value ==
One of the cool features little used in actionscript is the strict equality operator '===' what this does is evaluate if two pointers endup at the same address in memory, rather than the contents of that address. This is similar to the performance increase of looking at the mailing address on two envelopes rather than actually going to the address, knocking on the door to see who lives there. But this only works for pass by reference (Object) vrs pass value types (e.g. int, uint, boolean) and during comparions those that don't compare by value (e.g. Number, String).
Coding wise, I also like switch statements, they are clean visually and semantically, and AS3 has the neat feature to allow any type to act as a switch value, other languages like Java/.Net restrict case statements to primitives numbers, or strings.
I created a class to test raw performance of different types/approaches used in switch statements, primarily to determine whether strings (as passed by event e.g. Event.type), numbers or signals (as done by cogs) is faster approach, and if switch statements could use strict equality or by value.
Full Fledged Classes used as the case statement and switch are the fastest at close to 1/3 the time. This is great as it offers author time compile checking, strong typing at runtime. Lookups are likely by identity (===) instead of by value (==) as in data types even when those are marked static and constant, which means performance is about twice that of using a value comparison, in addition, since they are fullfledged objects they can contain all sorts of things (e.g. toString, operations).
Downside is that no numerical id is attached by number by default, so it's harder to index and later lookup these values when they exist in a random collection of some sort, but since it's a full fledged object, adding an id variable is easy.
In the class containing the switch, e.g.
//277ms for 100K
switch(stringVal){
case JanuaryStaticConst:
case "January":
break;
}
//177ms for 100K
switch(intVal){
case 22:
break;
}
//166 ms for 100K iterations
switch(objRef){
case Class.StaticVal:
break;
}
//98 ms for 100K iterations
static const var StaticVal = Class.StaticVal;
switch(objRef){
case StaticVal:
break;
}
Flash's compiler doesn't replace Class.StaticVal, with StaticVal so there is a lookup overhead. So it's recommended that you capture a reference in a static const (see recommendations at end)
For primitive data types (String, number, int, etc), strings are about 70% slower than any numbers, potentially the length of
the string may also impact the performance (not tested). Note that even making the string a static const string offered
no performance increase (though probably a significant memory performance increase) because your using value comparison (==) in the switch statement
versus identity (===).
The fastest numerical type, was an typically an int though this wasn't really repeatable, or significant. But might
make sense to use if your using it as bitflag.
Test Results for 100K iterations:
SwitchNumber 177
switchInt 176
switchUInt 170
switchString 277
switchStringConst 275
switchIntConst 175
switchCogSignal 166 <-- lookup of CogSignal.SIGNAL
switchCogSignalB 97 <-- 'cached' CogSignal.SIGNAL pointer (set via static constructor)
switchSwitchSignal 98 <- declaring it internally
Recommendations:
1) use a custom class, static const on the class
e.g.
//cache the value during class/static initialization
public static const C_0:SwitchSignal = SwitchSignal.C_0;
and later
public function switchSwitchSignal(sig:SwitchSignal):void{
switch(sig){
case C_0: //SwitchSignal.C_0, but no lookup overhead.
2) for raw data types use int, instead of (uint, Number).
Introspection in AS3
One of my design philosophies is leveraging technology to help create better technology. In design, this means using introspection to help validate the design elements, and autocreate classes. In coding this involves using introspection to help generate unit tests, and do class validation when you're doing things like function pointers, linked lists, static initialization.
One of the recent projects/framework named Cogs, a state machine (to be discussed more in future posts), uses function pointers extensively. So I use introspection to get the names dynamically of the states and validate the hierarchy, so coders can focus on developing the application instead of housekeeping. In languages in Java, introspection is quite powerful. In flash I was excited to see the potential of describeType(), which outputs an XML describing the class/instance.
Unfortunately in practice it's been limiting, introspection sees have to be marked as 'public' as anything else isn't visible. In particular protected and custom namespaces can't be introspected, even within the same namespace. Meaning a class can't introspect itself, even though it has access to the private/protected members of itself via normal code, or it's children, or utilities in the same package. This means custom namespaces and protected in regards to don't work like they do with variables, or functions.
This sucks. for-in is now limited to things on the prototype chain or plain objects, which are probably empty if your using standard classes. With describeTypes limitations seems crippled, limiting it's usefulness except for all but the simplest data types, or specifying everything by hand which is brittle.
Introduction
My name is Troy Gardner, I am the lead of TroyWorks a RIA professional services company specializing in flash related technologies, usually crammed to the gills with work. As such wear many different hats, from architect to programmer, to designer, information architect, project manager, janitor. Depending on the day and need.
This is my professional blog, in which I'll be talking primarily about Flash related technologies and development strategies that I use and help.
Keywords: Flash, Flex, Air, Actionscript (2.0, 3.0), RIA's, FDT, Eclipse, Virtualization, Red5, Remoting, AMF, OpenAMF, Design Patterns, Statemachines, as I run things of interest.
I have been developing in Flash since version 2, and also know Java, .Net and a little C. So tend to focus on the hard core scripting side of things, but I also deeply care about the usability of web applications. Typically I live somewhere between Flash's capability to innovate in UI and the data richness of Flex applications.
