Você está na página 1de 5

ActionScript 3.

0 and AVM2: Performance Tuning

ActionScript 3.0 and AVM2: Performance Tuning

Classes and Type Annotations

• 使用明確型別宣告可以增加效率並減少記憶體使用 (明確型別宣告是最佳化效率的
基礎)

class Circle
{
var radius : int; // STRONG (Best)
var color; // WEAK
}

Typing optimizes bytecode!

• Strong Reference
◦ 效率較高的存取
◦ 使用 . (dot operator) 存取成員
◦ 明確宣告型別
• Weak Reference
◦ 使用 hash lookup
◦ 沒有型別宣告

class Base extends Object


{
var x : int; // STRONG
var y : int; // STRONG
}
function a( o : Base ) // RETURN WEAK
{
return o.z; // WEAK
}
function a( o : Base ) : int // RETURN STRONG
{
return o.x; // STRONG
}

The Power of “int”

• int: 32 位元有號數
• uint: 32 位元無號數
• Number: 64 位元 IEEE 754 倍精度浮點數
ActionScript 3.0 and AVM2: Performance Tuning

Without Type Annotations

With Type Annotations

Typing with int, uint, Number

• 避免隱性轉型
• 注意數學運算可能造成隱性轉型的情況
• 有時候使用 Number 效率反而比較好

Strong Typing improves productivity

• 容易除錯
• 產生編譯期錯誤
ActionScript 3.0 and AVM2: Performance Tuning

Array Member Access

• Arrays 對於密集的部份 (dense portion) 使用 fast path 存取 (效率較好),對於其他


的部份使用 slow path 存取

var a : Array = [ 1, 2, 3, 4, 5 ];
a[ 1000 ] = 2010;
a[ 1001 ] = 2011;
a[ 2 ]; // FAST PATH
a[ 1000 ]; // SLOW PATH

Promotion of Numeric Types

• ECMA Script 的語法可能會造成 int/uint 被自動向上轉型成 Number

var i : int = 1;

// i+1 here will be a straight integer addition


var j : int = i + 1;

// i+1 here will require promotion to Number


print( i + 1 )

• Arrays 存取時對 int / uint 運算可能使得運算結果被向上轉型成 Number 而使用效


率較差的 Slow Path 方式存取 Arrays

var i : int;

// i*2 gets promoted to Number


for ( i = 0; i < 10000; ++ i )
{
a[ i * 2 ] = 0;
}

// Goes through fast path


for ( i = 0; i < 10000; ++ i )
{
a[ int( i * 2) ] = 1;
}
ActionScript 3.0 and AVM2: Performance Tuning

CSE (Common Sub-expression Elimination)

• VM 有時候無法幫你的程式最佳化,需要手動最佳化

// VM cannot make sure a's length will change or not


for ( var i : int = 0; i < a.length; ++ i )
{
processRecord( a[ i ] );
}

// Hand CSE was need if a's length is fixed


var n : int = a.length;
for ( var i : int = 0; i < n; ++ i )
{
processRecord( a[ i ] );
}

Method Closures

• 使用 Anonymous Function Closure 可能會產生一個 activation object 會對效率與


記憶體使用造成影響

class Form
{
function setupEvents()
{
var f = function( event : Event ) // activation object
{
trace( "my handler" );
}
grid.addEventListener( "click", f);
}
}

• Method Closures 是效率更高的做法

class Form
{
function setupEvents()
{
grid.addEventListener( "click", f );
}
function f( event : Event )
{
trace( "my handler" );
}
}
ActionScript 3.0 and AVM2: Performance Tuning

Compound Strings

var s : String = "Hello, ";


var s : String

Φ Hello,
prefix

s += "world, ";
var s : String

Φ Hello, world,
prefix prefix

s += "from AS3!";
var s : String

Φ Hello, world, from AS3!


prefix prefix prefix

Você também pode gostar