Caching images in your Flex application can greatly improve performance and reduce the overhead of loading external resources.
And I’m not simply talking about using the
cacheAsBitmap property to improve rendering performance or the
cachePolicy property to speed up animations. I’m talking about caching the actual bitmap data of an image.
To get started, you’ll need a hash map to store the image data. A
Dictionary or an associative array will also work just fine.
Loading an image for the first time is the same as usual. You create a new
Image object and add a listener for the
Once the image has finished loading, you add a copy of the bitmap data to the hash map using the image URL as the hash key:
Now we can use the image as many times as we want without ever having to load it again!
To take advantage of this, you’ll need to check the hash map every time you create a new image (or change the
source property) to see if you’ve already cached it:
And that’s it!
If you have an application that loads a large number of images you may want to limit the number of cached images to prevent the Flash player memory usage from getting out of hand, but in general caching even several dozen large images only results in a slightly increased footprint.