BetaDesigns( Blog ) Flex and Component Development

14Oct/090

Code Optimization tricks

Collapse literal values

 
  var a : uint = b + ( 10024-200 ) / 2;//195msvar a : uint = b + 412;//47ms
 

Multiplication is faster than Division
nice explanation of using multiplication for division here

 
  result = num / 4;//382ms
√ result = num * 0.25;//132ms
 

Use Implicit type casting

 
  var a : Point = points[ i ] as Point;//179msvar a : Point = points[ i ];//109ms
 

Test variables before methods in statements

 
  if(method( ) && variable )//211msif( variable && method() )//7ms
 

Declare varialbes outside of loops

 
for( var i : int = 0; i < arr.length; i ++ )//515ms
  var i : int = 0;
  var arrLength : int = arr.length;
√ for( ; i < arr.length; i ++ )//39ms
 

Thowing erors takes time.

 
  try{ isNull.x = 3; }catch( e : Error ){ }//78msif( isNull ) { isNull.x = 3; }//0ms
 

Use references instead of full paths or the with operator.

 
  with( sprite.graphics ){ ...};//164msvar g : Graphics = sprite.graphics;//23ms
 

Use Object Pools

Bitwise tricks
Bitwise maths on wikipedia Boolean algebra on wikipedia
polygonal labs bitwise gems

 
val = num | 0; //Same as Math.floor();
val = num + 0.5 | 0; // Rounds positive numbers.
//Divide by power of two
val = num >>1; //Divide by 2 and floor.
val = num / 32 is the same as val = num >> 5
val = 65535 >> 8; //255
//actual value is 255.996...
//But it is being floored as well
i = (x^(x>>31)) - (x>>31);//about 2700% faster than Maths.abs();
 
if(++count&1){}//alternation i need to check this one.
 
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

(required)

No trackbacks yet.