Construct, init, reset
That, in a nutshell is your three-step guide to instance class-creation happiness in AS3. Let me explain:
public function SomeClass ( name:String ) { _name = name; _init(); } private function _init ():void { // your initialisation code here... reset(); } public function reset ():void { // your reset code here... }
This public - private - public approach to initialising your AS3 objects will make you life SO much easier. Let me tell you why:
- Constructor
Every new AS3 class instance needs to be created via it’s constructor method - fine, that has to be stage 1 - but code in it should be kept to a minimum, just save off any passed-in params to private variables and call the init() method as soon as you can. This is because char-for-char AS3 constructor methods use more processing power than all other AS3 class methods. Keep your overheads low by calling init() asap. - Private init() method
So, because a private init() method is just a regular old method, to assign the bulk of the initialisation code to it is gonna make your code run faster. Anything that needs to be done just once at the start of a new class instance, do it here and not in the constructor. Then call… - Public reset() method
Repeatable initialisation code should be assigned to your public reset() method. The advantage here is that reset() can be called repeatedly following instance creation, meaning that if, down the line, you need to keep your class instance but set params back to starting defaults - like , say, visible to true, x & y to 0, etc, etc - you can just call reset() and bingo! You can instantly reuse the class instance sensibly without having to worry about refactoring or garbage collection or whatever.
There is a slight drawback in this method in that if you subclass your resettable class the the superclass reset() method will get called twice on initialisation, three times if you subclass your subclass. This is a minor overhead but, I think, is a tiny loss in contrast to the gain made in refactoring and garbage collection
Quite why the constructor method is processor-intensive I’ll have to look into. Take it from me though: it is. If I have learned one things from these past 4 months of AS3 exploration it is always, always, always to initialise new class instances the “construct, init, reset” way.
Tags: ActionScript3, AS3, FlashBrighton
March 13th, 2008 at 9:17 pm
thanks for this writeup…
there is a loose benchmark regarding init vs. constructor code at http://blog.pixelbreaker.com/flash/as30-jit-vs-interpreted/.
Savings: 100ms!
March 13th, 2008 at 9:17 pm
thanks for this writeup…
there is a loose benchmark regarding init vs. constructor code at http://blog.pixelbreaker.com/flash/as30-jit-vs-....
Savings: 100ms!
March 17th, 2008 at 10:00 pm
no worries ragaskar, hoped it helped. and thanks for the url, very useful. :)
March 17th, 2008 at 10:00 pm
no worries ragaskar, hoped it helped. and thanks for the url, very useful. :)