Home Tutorials Forums Articles Blogs Movies Library Employment Press
Old 12-17-2007, 05:03 AM   #41
matbury
What's up pussycat?
 
matbury's Avatar
 
Join Date: Dec 2006
Location: Toronto, Canada
Posts: 1,990
Default

Here's a quickie:

How to find the next object in an array by looping through and comparing the current object against each object in the array.

All the bTexts[?] objects are the same [object Sprite] so if you use:

if(currentWord == bTexts[i]) - it will always return true, so you have to use a deep comparison operator '==='. This will find differences between the objects so that only an exact match will return true:

ActionScript Code:
function gotoNextWord():void {     for(var i:uint = 0; i < bTexts.length; i++){         if(currentWord === bTexts[i] && i < bTexts.length - 1){             currentWord = bTexts[i + 1];             bTexts[i] = null;             setNextWord();             checkScore();             break;         }         // so you don't return a null object reference on the last one:         if(currentWord === bTexts[i] && i == bTexts.length - 1){             bTexts[i] = null;             checkScore();         }     } }
__________________
http://matbury.com/
matbury is offline  
Old 12-22-2007, 12:37 AM   #42
matbury
What's up pussycat?
 
matbury's Avatar
 
Join Date: Dec 2006
Location: Toronto, Canada
Posts: 1,990
Default AS 3.0 Optimisation

Optimise your code:

Quote:
Originally Posted by Daedalus View Post
Ok Here it is. I just spent the past 3 hours going through tons of sites, blogs and PDFs looking for good coding rules for AS3.

I have found 22 rules that are proven to improve performance but there could be more. Feel free to keep adding numbers eg.23,24 if you find any more rules that result in performance increases.

Hopefully the 3 hours I spent doing this will be repayed by not having to spend as much time refactoring inefficient code.

Actionscript Code Optimization Rules

1) Don't evaluate object/array lengths on each iteration of a loop
2) i=i+1 and i+=1 are faster than i++
3) Instead of dividing by 2, multiply by 0.5

Eg.

var newPosition:Number = parentObject.width * .5;
var len:int = manyObjects.length;
for (var i:int = 0 < len; i+=1)
{
manyObjects[i].x = newPosition;
}

4) never use Math.floor. It's slow as frak. Instead cast the number as a type int

5) don’t use Math.ceil. Cast to an int and add 1 int(1.5)+1

6) don’t use Math.abs() (distance of number from 0) instead use the following “if (n < 0) n = -n;” Where n is the number you want to find the absolute value of.

7) if you can do an operation outside a loop then do it!
Eg. Assign constant to variable to use in loop instead of doing assignment inside the loop.

8) declare variables on the same line
Eg var v1:Number=10, v2:Number=10, v3:Number=10, v4:Number=10, v5:Number=10;

9) use bitwise operations for division and multiplication

Eg.

var val1:int = 4 * 2;
var val2:int = 4 * 4;
var val3:int = 4 / 2;
var val4:int = 4 / 4;

becomes>

var val1:int = 4 << 1;
var val2:int = 4 << 2;
var val3:int = 4 >> 1;
var val4:int = 4 >> 2;

10) store objects retrieved from arrays in typed variables before calling properties and methods on it.

images[index].getPixel(x,y);

becomes>

var image: BitmapData = images[index];
image.getPixel(x,y);

11) General rule of thumb usage for dealing with numbers. (see end of post for more info)
Use ints whenever possible over Number.
Always use boolean over int whenever possible
Try not to use uint.

12) Coerce array index values to ints when index value is calculated.

Eg.

a[int(i*2)] = 1;

13) Do not use inner functions unless there is no alternative



14) Don’t put performance-intensive code in class initialization: (initialization functions are interpreted instead of JIT which is used for al other functions)

Eg.
class Sieve
{
var n:int, sieve:Array=[], c:int, i:int, inc:int;
set_bit(0, 0, sieve);
set_bit(1, 0, sieve);
set_bit(2, 1, sieve);
for (i = 3; i <= n; i++) set_bit(i, i & 1, sieve);
c = 3;
do { i = c * c, inc = c + c; while (i <= n) { set_bit(i, 0, sieve); i += inc; } c += 2;
while (!get_bit(c, sieve)) c++; } while (c * c <= n); }

15) Always used weak references for event listeners to aid garbage collection (final augment true)

Eg. stage.addEventListener(Event.CLICK,handleClick,fal se,0,true);


16) 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.

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

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

package somepackage{
public const somevar:int;
}

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

var n:Graphics = sprite.graphics;
n.clear();
n.beginFill(0x000000);
n.drawRect(0,0,10,10);
n.endFill();

another example>

//not so good
var person:Person;
if (person.firstName == “Matt” || person.firstName == “Ted” ||
person.firstName == “Alex”)

//much better
var fname:String = person.firstName;
if (fname == “Matt” || fname == “Ted” || fname == “Alex”)


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

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

var someclass:Class = object.reflect();

(this method is over 5000% FASTER!)

20) MAKE SURE EVERYTHING IS TYPED!

All variables, member and local
All function return values
All parameter types in functions or error handlers
All loop counters
If you see “var”, better see “:<type>”
Even if your class is dynamic
VM can take advantage of slots for members that are pre-compiled
New properties will require the hash lookup

21) If type is unknown, check before using.
Try coercing the variable to the type you want before accessing
An VM error can be 10x slower than the time it takes to execute the test or coercion.

22) Avoid spaces in arrays. (Keep them dense)
Eg. var a:Array = [1,2,3,4,5];
a[1000] = 2010; //bad, makes lookup slower


Performane of different number types for different assignments.

http://www.gskinner.com/blog/archive...in_as3_in.html

Assignment ( var a:TYPE = 0.5; )
int: 56-83ms
Number: 26-43ms
uint: 57-92ms

Predictably, Number is faster for fractional assignments, as the value does not need to be converted to an integer.

Division ( var a:TYPE = i/2; )
int: 60-105ms
Number: 34-64ms
uint: 184-278ms

Number is a much faster type for division, as expected from Sho's post. uint trails badly.

Multiplication ( var a:TYPE = i*2; )
int: 78-129ms
Number: 39-64ms
uint: 207-280ms

Similar results to division. I thought int might perform better as the value would never have to be converted to a float (whereas in division it would).

Addition ( var a:TYPE = i+2; )
int: 31-49ms
Number: 44-55ms
uint: 85-113ms

As expected from the plain iterator test, int is slightly faster for integer addition.

Bitshift ( var a:TYPE = i<<1; )
int: 31-63ms
Number: 61-114ms
uint: 71-130ms

int outperforms Number fairly handily in bit operations, this is likely because Number needs to be converted into an int to have bit operators applied. This is the only test so far that uint does passably well in (other than assignment).

Heres the source for all these rules

http://blog.andre-michelle.com/2005/...ns-suggestions

http://www.onflex.org/ACDS/AS3TuningInsideAVM2JIT.pdf

http://www.adobe.com/devnet/flashpla...anagement.html

http://www.adobe.com/devnet/flashpla...ollection.html

http://www.gskinner.com/blog/archive...in_as3_in.html

http://www.gotoandplay.it/_forums/viewtopic.php?t=179

http://lab.polygonal.de/2007/05/10/b...-integer-math/

http://www.onflex.org/ACDS/AS3TuningInsideAVM2JIT.pdf

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

http://www.adobe.com/devnet/flex/art...fm_as3perf.pdf

http://rozengain.com/?postid=35

This desire for efficiency makes me hungry! Time for Dinner! I will add more rules if i find any more worth noting.
__________________
http://matbury.com/
matbury is offline  
Old 12-25-2007, 11:34 PM   #43
h00d
Registered User
 
Join Date: Dec 2007
Posts: 78
Default

This thread is going to get wildly out of control. Maybe we should use this thread to link to the appropriate threads. That way when questions are asked they are all located in the relevant thread. My two cents.

Links and descriptions of the thread should be sufficient, no?
h00d is offline  
Old 12-30-2007, 09:34 PM   #44
matbury
What's up pussycat?
 
matbury's Avatar
 
Join Date: Dec 2006
Location: Toronto, Canada
Posts: 1,990
Default

Quote:
Originally Posted by h00d View Post
This thread is going to get wildly out of control. Maybe we should use this thread to link to the appropriate threads. That way when questions are asked they are all located in the relevant thread. My two cents.

Links and descriptions of the thread should be sufficient, no?
I reckon we're gonna need a wiki on this one!

I'm curious - Which wiki do Adobe and Papervision and a bunch of others use?
__________________
http://matbury.com/
matbury is offline  
Old 01-10-2008, 07:29 AM   #45
FrodoBaggins
Fellowship of the Script
 
Join Date: Jan 2006
Location: the Netherlands / heading to the UK
Posts: 629
Default

Hi guys!

Sorry for my long time of absence, in fact it will even be longer... I'm smack in the middle of moving to the UK, work is crazy and relaxing is a word that is starting to loose it's definition. Anyway, hopefully in a month or two I'll be able to contribute a bit more here.

- FB.
FrodoBaggins is offline  
Old 01-13-2008, 02:29 PM   #46
Arni Ingason
Registered User
 
Join Date: Jan 2008
Posts: 18
Thumbs up

hi matbury
I am trying to use your LoadXML class
I put the following code in my fla file:

import Load_XML;
import flash.events.Event;


var XML_doc:LoadXML = new LoadXML("SomeFile.xml");
XML_doc.addEventListener(LoadXML.LOADED, loadedHandler);

function loadedHandler(event.LOADED):void
{
trace("Hi");
}


But this dose not work
What am I doing wrong
Some help would be apriciated
Arni Ingason is offline  
Old 01-15-2008, 01:16 AM   #47
matbury
What's up pussycat?
 
matbury's Avatar
 
Join Date: Dec 2006
Location: Toronto, Canada
Posts: 1,990
Default

This should work:

ActionScript Code:
import LoadXML; // the class name has to match the filename and the package name // import flash.events.Event; // this isn't necessary in an FLA file, only in AS class files. var XML_doc:LoadXML = new LoadXML("SomeFile.xml"); XML_doc.addEventListener(LoadXML.LOADED, loadedHandler); XML_doc.addEventListener(LoadXML.FAILED, failedHandler); // always handle the alternatives function loadedHandler(event:Event):void // I've used eventDispatcher so it's an 'Event' { trace(event.target.xml); this should trace the contents of SomeFile.xml trace("Hi"); } function failedHandler(event:Event):void // to let you know if it didn't work! { trace(event); trace("Oops!"); }
__________________
http://matbury.com/
matbury is offline  
Old 01-15-2008, 02:28 AM   #48
hangalot
lala
 
hangalot's Avatar
 
Join Date: Feb 2002
Location: on the road
Posts: 2,858
Default

i vote we close this thread so people ask general questions on the actual board.
if someone wants to add a new tip create a new thread and ask a mod to merge it into this one.
any objections?
__________________
oi poloi
http://www.memorphic.com/news/
hangalot is offline  
Old 01-15-2008, 07:52 PM   #49
hangalot
lala
 
hangalot's Avatar
 
Join Date: Feb 2002
Location: on the road
Posts: 2,858
Default

no objections so i am closing
__________________
oi poloi
http://www.memorphic.com/news/
hangalot is offline  
Closed Thread


Thread Tools
Display Modes Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
shared whiteboard with actionscript 3.0 flashyBird ActionScript 3.0 2 10-12-2007 05:13 AM
Animations in ActionScript 3.0 teenup ActionScript 3.0 6 09-17-2007 12:11 PM
PHP, Actionscript 3.0 and Å Ä Ö characters latrixie ActionScript 3.0 7 08-29-2007 08:41 AM
Actionscript 3.0 Programmer Insanemitch Projects and Positions 0 08-28-2007 08:21 PM
Preloader for actionscript 3.0 rysotope ActionScript 3.0 3 07-10-2007 04:58 PM


All times are GMT. The time now is 01:18 AM.

///
Follow actionscriptorg on Twitter

 


Powered by vBulletin® Version 3.8.5
Copyright ©2000 - 2014, Jelsoft Enterprises Ltd.
Ad Management plugin by RedTyger
Copyright 2000-2013 ActionScript.org. All Rights Reserved.
Your use of this site is subject to our Privacy Policy and Terms of Use.