Flexcomps’s Weblog

Improve Performance with BitmapData.lock( )

Posted on: October 10, 2008

While reading a book i come to a very interesting topic which i would like to share here

———————–

By default, The bitmap instances that reference a given BitmapData object are notified every time setPixel32( ) or setPixel( ) is called on that object. When setPixel32( ) or setPixel( ) are used in rapid succession within the same frame cycle—such as when setting the color of every pixel in a bitmap—these notifications can reduce performance. To improve performance, we can use the BitmapData class’s instance method lock( ).

Calling lock( ) on a BitmapData object forces ActionScript to not notify dependent Bitmap objects when executing setPixel32( ) or setPixel( ). Hence, before using setPixel32( ) or setPixel( ) in rapid succession, always call lock( ). After calling lock( ), assign all desired pixel color values; then call the BitmapData( ) class’s instance method unlock( ). Calling unlock( ) instructs ActionScript to notify all dependent Bitmap objects as necessary.

Example below demonstrates the approach. The example uses a loop to assign a random color to every pixel in a 500 × 500 BitmapData object. Notice the call to lock( ) before the loop and unlock( ) after the loop.


// Create the bitmap
var imgData:BitmapData = new BitmapData(500, 500, true, 0x00000000);
var bmp:Bitmap = new Bitmap(imgData);
// Invoke lock( )
imgData.lock( );
// Set pixel color-values
var color:uint;
for (var i:int = 0; i < imgData.height ; i++) {
for (var j:int = 0; j < imgData.width; j++) {
color = Math.floor(Math.random( )*0xFFFFFFFF);
imgData.setPixel32(j, i, color);
}
}
// Invoke unlock( )

In tests, when running above Example in the release version of Flash Player on a computer with a Pentium 4 2.6-GHz processor, a single iteration of the loop takes approximately 100 ms. Without lock( ), a single iteration takes approximately 125 ms. That is, code runs approximately 20% faster when lock( ) is used.

2 Responses to "Improve Performance with BitmapData.lock( )"

And performance will get better for each additional Bitmap instance (or bitmap fill) that references that bitmap.

[…] Here is the original post: Improve Performance with BitmapData.lock( ) […]

Leave a comment

October 2008
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031  

Blog Stats

  • 326,382 hits