Wednesday, December 10, 2008

Flex application slows down over time

I have been working on a simple Flex application that draws many rectangles in one of five different colors on a Canvas. I created a Sprite object which I used to do the drawing. At first I was drawing each rectangle like this:
var g:Graphics = sprite.graphics;
g.beginFill(0xff00001);
g.drawRect(002020);
g.endFill();

But I noticed when I was drawing hundreds of rectangles over time (using a Timer object to paint new rectangles every few hundred milliseconds) this got to be pretty slow.
So my next attempt to improve performance was to cache a BitmapData object for each rectangle (they are all the same size) of a certain color:
// initialize the cache in the constructor
var cache:Dictionary = new Dictionary();

// paint each rectangle:
var color:uint = 0xff0000;
var data:BitmapData = cache[color];
if (data == null) {
    data = new BitmapData(2020false, color);
    cache[color= data;
}
g.beginBitmapFill(data);
g.drawRect(002020);
g.endFill();

This definitely improved the performance a lot, now I can draw hundreds of rectangles, but I still noticed that the rendering would slow down after a few minutes. Thankfully I came across this posting on Nabble: http://www.nabble.com/-INFO--FLEX-Effects-slowing-down-with-time-td20770945.html

Perhaps this is obvious to most people, but I was never calling graphics.clear()! So over time my sprite's graphics object was getting filled with thousands of rectangles to paint. As soon as I added sprite.graphics.clear() to my updateDisplayList() function it worked perfectly.

1 comment:

Anonymous said...

Thank you, this was very helpful! I had the same problem today when I was still learning the Flash.