Why cacheAsBitmap is bad!

One of the feature I would really love to see in a future release of the Flash Player is a native rasterizer for display objects. Imagine something like :

1. myMovieClip.rasterize = true;

This code would rasterize your DisplayObject as an animated PNG. It would bring crazy improvements for designers and coders who want to improve the rendering performance of any animation. This would be in fact the same behavior as the Banana Slice component I talked about.

When talking about this, some people could think "Well, you have cacheAsBitmap for that". The reason why such a feature would rock is mainly due to the fact that cacheAsBitmap is very dangerous. Well, it won't hurt you :) , but it can definitely hurt your application performance.

As I said before, when cacheAsBitmap is set, the DisplayObject is cached as a bitmap on memory and the Flash Player is using this copy to render it on screen. The main problem that we have here is that if you do more than moving this DisplayObject on x and y, for each frame the Flash Player is updating the cached copy on memory before updating the screen. So if you apply any rotation, scale, alpha, or even if you have any key frames in your DisplayObject you will get performance decrease.

Hopefully, you can bypass this limitation by creating a BitmapData by yourself, draw the MovieClip on it, and pass it to multipe Bitmap instances. So let's take a simple example, in the folllowing movie, when you click on the "cacheAsBitmap" button, I create multiple instances of an Apple MovieClip, set cacheAsBitmap, and move them on screen :

01. var apple:Apple;
02.   
03. for (var i:int = 0; i< 100; i++)
04. {
05. apple = new Apple();
06.   
07. apple.cacheAsBitmap = true;
08.   
09. addChild ( apple );
10. }

When you click on the "draw" button, I first create an instance of the apple MovieClip, draw it on a BitmapData and then create Bitmap instances linked to the one and unique BitmapData instance :

01. var source:AppleSource = new AppleSource();
02.   
03. var buffer:BitmapData = new BitmapData ( source.width, source.height, true );
04.   
05. buffer.draw ( source );
06.   
07. var bitmapApple:BitmapApple;
08.   
09. for (var i:int = 0; i< 100; i++ )
10. {
11. bitmapApple = new BitmapApple( buffer );
12.   
13. addChild ( bitmapApple );
14. }

You can download the sources here

你可能感兴趣的:(bitmap)