Tip Of The Day

62 posts

Flag Post

So, I was thinking, as any other programming language, there are a ton of little things in Actionscript 3 and its API you might never notice. I thought it would be neat to have a thread with a new tip every day. Ideally, anyone could contribute tips.


Example Tip:

Adding Text to a TextField
Date: 1/4/2012
Complexity: Easy

When adding text to a TextField use the appendText(newText:String) method instead of myTextField.text+="additional text"; for optimal performance.


That’s just a very simple example of course, tips could range from that level to any difficultly level. Good idea, bad idea?

 
Flag Post
Index:
 
Flag Post

[Reserved]

 
Flag Post

[Reserved]

 
Flag Post

if/else is faster than ?: due to a compiler bug

keep things limited to about 1 operation per statement (everything from a { to ; or from a ; to ;) to avoid compiler bugs that reduce speed (nJIT will optimize these to give you a larger advantage than doing multiple operations per statement, most particularly on ints)

don’t increment/decrement uint variables in array-access, in conditions or in other statements. a compiler bug will convert from uint to Number back to uint. on its own line, this bug does not exist. int does not suffer from this bug.

 
Flag Post

Extend the most basic subclass:
Complexity: Intermediate (since it requires some knowledge of the available classes).

Because I’m sick of reading examples of people who extend MovieClip only to store x, y and a couple numbers and arrays; If a subclass (or even Object) has all the necessary for your needs, use it.


Use bitwise operators:
Complexity: Easy.

They’re faster. Just make sure to use parenthesis for everything or it will return wrong values.
Common usage:

Even number: (n&1)==0
Math.abs() n=(n<<0)?-n:n;
Casting int n>>0
Divide by power of 2n>>N Where N is the power of two.
ie, width>>1 is the same as width*.5.
Multiply by power of two n<<N Same as above.


Knowing if a pixel of a BitmapData has contents:
Complexity: Intermediate. (Since BitmapData manipulation isn’t for newbies, the evaluation itself is rather easy).
trace(((myBitmapData.getPixel32(x,y))>>24&0xFF)/0xFF)


I may add some more later.

Also, Kong’s forums aren’t the best place for this; the post will break after some lines, plus it doesn’t allow to use spoiler tags.

 
Flag Post

Enable caching for MovieClips that won’t need to be redrawn
Complexity: Easy

If MovieClip has no internal changes, and is not scaled or rotated, it can be cached as a bitmap image by setting myMC.cacheAsBitmap = true;

This can greatly increase performance when using large or complex MovieClips.


quick null-check on property access to avoid compiler error
Complexity: Intermediate? (Noobs don’t know ternary operator)

object?object.property:null


Fast unordered array splicing
Complexity: Intermediate

If this is done in a loop, you will want to make sure you go over this index again (by decrementing the iterator if in a forward loop, and incrementing it in a reverse loop) since a new element will be in its place.

//quickly removes element i from the array. does not maintain order.
someArray[i] = someArray[someArray.length-1];
someArray.length--;
 
Flag Post

Lines Visible in TextField
Complexity: Easy

To see how many lines of code are visible in a multiline scrollable TextField:

var numLinesVisible:int = myTextField.bottomScrollV-myTextField.scrollV+1;
 
Flag Post

@truefire, make sure people know that if they do that in a for loop, they want to decrement the loop var. Some developers blindly using that code might forget to to that. (Fixed, thx truefire!)


Textfield Changing Performance
Complexity: Easy

Don’t update when you don’t have to. A lot of people make the mistake of setting a textfield’s value every frame. Only set it when it changes.

if(textfield.text != newText) textfield.text = newText;
 
Flag Post

Clean after yourself
Complexity: Easy.

Whenever you add a listener, type a line that removes it (or use weak listeners).
Whenever you create an object, make sure it’s destroyed at some point.

A simple way to keep this organized is to throw everything in a REMOVED_FROM_STAGE handler, although it’s better if you kill the objects and listeners as soon as they stop being required.


Don’t make unnecessary variables that you’ll only use once
Complexity: Easy

Bad code:

var green:uint=0xFF00;
var alpha:Number=0.8;
var blurX:Number=3.5;
var blurY:Number=5.5;
var strength:int=3;
var quiality:int=3;
var glow:GlowFilter=new GlowFilter(green,alpha,blurX,blurY,stength,quality);
filters=[glow];

Good code

filters=[new GlowFilter(0xFF00,1,3.5,5.5,3,3)];
 
Flag Post

Using ENTER_FRAME listeners
Complexity: Easy
Do not add an ENTER_FRAME listener to 100 different objects. Rather, add one listener to the stage, and loop through the objects in your game with it. For several reasons, 1. it’s a lot faster, (i.e. looping is more efficient than recursion), 2. it’s more centralized (easy to debug), 3. makes pausing very easy 4. no dangling enter frame listeners(very not good) 5. your code will be easier to follow 6. ability to add/remove features more easily without hassle. The list goes on.

 
Flag Post

Copying Data To The Clipboard
Complexity: Easy

To copy data to the clipboard, simply use System.setClipboard(string:String) method. Be careful though – for security reasons, it will only work in response to a user event like a MouseEvent or a KeyboardEvent. Also be sure to import flash.system.System.

 
Flag Post

Originally posted by BobTheCoolGuy:

Also be sure to import flash.system.System.

flash.system.system_resources.system_files.system_api.System;


also, placing \ as the final character after // will cause the next line to be commented too

 
Flag Post
Originally posted by skyboy:

Originally posted by BobTheCoolGuy:

Also be sure to import flash.system.System.

flash.system.system_resources.system_files.system_api.System;


Hmm? What are you saying?

 
Flag Post

Originally posted by BobTheCoolGuy:

Hmm? What are you saying?

i’m commenting on the naming redundancy of a System class in the system package

 
Flag Post

Centering an object
Complexity: Easy

//implying the object’s bounds are (0,0,w,h)
Subtract the size of the object from the area where you want to center it, then divide everything by two. ie:
Edited: See post below for an example. ▼

 
Flag Post

Originally posted by Senekis93:

Centering an object
Complexity: Easy

//implying the object’s bounds are (0,0,w,h)
Divide by two the area where you want to center the object and subtract half the size of the object. ie:
x=(stage.stageWidth>>1)-(width>>1);
y=(stage.stageHeight>>1)-(height>>1);

x = (stage.stageWidth - width) * 0.5;
y = (stage.stageHeight - height) * 0.5;

is faster. you don’t convert 4 doubles to an int, convert them to a double, then subtract them. the compiler’s quirks are quite nasty when it comes to speed.

 
Flag Post

So bitwise stuff isn’t super fast as they sell it? I remember that most sites that talk about bitwise operators say that doing two or three bitwise operations is still faster than a single “normal” arithmetic one.

Or that stands true and the only issue here is the float→int stuff?
Anyway, thanks for the tip, I’ll start doing it that way from now on.

I’m already liking this thread.

 
Flag Post

Originally posted by Senekis93:

Or that stands true and the only issue here is the float→int stuff?
Anyway, thanks for the tip, I’ll start doing it that way from now on.

I’m already liking this thread.

bitwise is faster than operators on double, but only if the bitwise stuff is done on ints

the killer is this: convert_i, shift, convert_d, subtract

you may get away with using >>1 after the subtraction, but there’s still room for the compiler to output shoddy code. besides, it gets converted back to double for assignment then multiplied by 20 and converted to int to store as twips internally. just don’t rely on the MXMLC compiler, they don’t really do a good job with it. but no one else is in a hurry to make a replacement

 
Flag Post

Performance tips.

 
Flag Post
Originally posted by Senekis93:

Performance tips.

Regarding the first tip, it is true that native code in FP will run faster than AS3. But a distinction needs to be made between native code and all code that is in the flash.* packages (which the author suggests is entirely native). Native code is that which is implemented in C++ within Flash Player. Just because a function is in the flash.* package does not mean it is implemented natively and, in fact, a lot of code in playerglobal is not simply intrinsic definitions which defer to native code in FP. Rather, a lot of of its implementations are done with ABC, just like anything you write in AS3 will be compiled to. Whoever at Adobe authored these obviously thought there was not a significant gain from deferring this code to native functions versus the translation from ABC to machine code. And also don’t think that all of this code is optimized for your use case. Take for instance the Point class, which has implementations in ABC and which is completely unoptimized for performance.

Oh, and ints are floats.

 
Flag Post

Originally posted by BigJM:

Oh, and ints are floats.

they are not1. i have the source code to prove it. also, in version 16 (11.2? 11.1?) Adobe expects to have finished float and float4 implementations. they will come in their own classes (named, with case) and the Math.* methods have been implemented on both Number and float/float4 to make it more consistent, since the Math class can’t override methods for float/double. the float class will also come with a natively implemented inverse square root method.

1. except in cases where over 29 bits of accuracy are required (unless you’re using the 64bit player or the player was compiled with MSVC, then it’s 53 bits of precision for int; which you can’t exceed.)

 
Flag Post

Yeah that was stupid; I don’t know why I said that. Why would an integer have a floating decimal haha.

 
Flag Post

When using sessions in C# do not create session for each variable rather then put all variables in class and then create its object in page load to access its variable, in this way you can save memory of server.

 
Flag Post

Use int, not String

When possible, use int instead of String. I don’t know the exact numbers, but there’s a difference.

Some people use strings to make it easier to know what they’re referring to.
If that’s the case, instead of doing loadWeapon("Dragunov");
try something like loadWeapon(DRAGUNOV); where DRAGUNOV is a constant of type int.