重複使用物件

盡可能重複使用物件,而不要重新建立它們。

另一個最佳化記憶體的簡單方式是重複使用物件,並盡可能避免重新建立它們。例如,在迴圈中,請勿使用下列程式碼:

const MAX_NUM:int = 18; 
const COLOR:uint = 0xCCCCCC; 
 
var area:Rectangle; 
 
for (var:int = 0; i < MAX_NUM; i++) 
{ 
    // Do not use the following code 
    area = new Rectangle(i,0,1,10); 
    myBitmapData.fillRect(area,COLOR); 
}

在每個迴圈循環中重新建立 Rectangle 物件會使用較多的記憶體且較為緩慢,因為每次循環都會建立新的物件。請使用下列方式:

const MAX_NUM:int = 18; 
const COLOR:uint = 0xCCCCCC; 
 
// Create the rectangle outside the loop 
var area:Rectangle = new Rectangle(0,0,1,10); 
 
for (var:int = 0; i < MAX_NUM; i++) 
{ 
    area.x = i; 
    myBitmapData.fillRect(area,COLOR); 
}

上一個範例所使用的物件對記憶體的影響相當小。下一個範例示範重複使用 BitmapData 物件,以節省較多的記憶體。下列程式碼會建立拼貼效果會浪費記憶體:

var myImage:BitmapData; 
var myContainer:Bitmap; 
const MAX_NUM:int = 300; 
  
for (var i:int = 0; i< MAX_NUM; i++) 
{ 
    // Create a 20 x 20 pixel bitmap, non-transparent 
    myImage = new BitmapData(20,20,false,0xF0D062); 
  
    // Create a container for each BitmapData instance 
    myContainer = new Bitmap(myImage); 
  
    // Add it to the display list 
    addChild(myContainer); 
  
    // Place each container 
    myContainer.x = (myContainer.width + 8) * Math.round(i % 20); 
    myContainer.y = (myContainer.height + 8) * int(i / 20); 
}
備註: 使用正值時,將四捨五入的值轉換為 int 會比使用 Math.floor() 方法更加快速。

下列影像會顯示點陣圖拼貼的結果:

檢視完整大小的圖形
點陣圖拼貼的結果

最佳化的版本會建立單一 BitmapData 實體,讓多個 Bitmap 實體參考,並且產生相同的結果:

// Create a single 20 x 20 pixel bitmap, non-transparent 
var myImage:BitmapData = new BitmapData(20,20,false,0xF0D062); 
var myContainer:Bitmap; 
const MAX_NUM:int = 300; 
  
for (var i:int = 0; i< MAX_NUM; i++) 
{ 
    // Create a container referencing the BitmapData instance 
    myContainer = new Bitmap(myImage); 
  
    // Add it to the display list 
    addChild(myContainer); 
  
    // Place each container 
    myContainer.x = (myContainer.width + 8) * Math.round(i % 20); 
    myContainer.y = (myContainer.height + 8) * int(i / 20); 
}

此方法可節省大約 700 KB 的記憶體,對於傳統行動裝置而言,這節省相當大量的記憶體。每個點陣圖容器都可加以操作,而不須使用 Bitmap 屬性來修改原始 BitmapData 實體:

// Create a single 20 x 20 pixel bitmap, non-transparent 
var myImage:BitmapData = new BitmapData(20,20,false,0xF0D062); 
var myContainer:Bitmap; 
const MAX_NUM:int = 300; 
  
for (var i:int = 0; i< MAX_NUM; i++) 
{ 
    // Create a container referencing the BitmapData instance 
    myContainer = new Bitmap(myImage); 
  
    // Add it to the DisplayList 
    addChild(myContainer); 
  
    // Place each container 
    myContainer.x = (myContainer.width + 8) * Math.round(i % 20); 
    myContainer.y = (myContainer.height + 8) * int(i / 20); 
  
    // Set a specific rotation, alpha, and depth 
    myContainer.rotation = Math.random()*360; 
    myContainer.alpha = Math.random(); 
    myContainer.scaleX = myContainer.scaleY = Math.random(); 
}

下列影像會顯示點陣圖變形的結果:

檢視完整大小的圖形
點陣圖變形的結果