Nov
8

GD Library Garbage Collection

Programming/PHP

If you have visited the LazyMoon title page (with a recent browser and JavaScript active), you would have noticed the ability to dynamically create a wallpaper form the now symbolic silhouette design. One thing very few people notice is that the wallpapers are automatically sized to match your screen resolution. Meaning I haven’t just designed every possible combination, but programmed a script to create your wallpaper when you request it.

This consumes an unholy amount of memory. To the extent where I suspect my host may get a little upset if too many people request a wallpaper at once.

What is concerning is that PHP doesn’t automatically garbage collect GD resources stored in memory. If someone cancels their request or the script terminates early, that resource will not be destroyed. This only has to happen a handful of times before the memory is filled and I get a unhappy letter with some very large numbers.

If you use the GD library and don’t have a garbage collection function, you are playing dangerously. To get around this, we can write a function and use PHP’s register_shutdown_function to manually free un-destroyed resources.

The code snippet I use is:

function gd_garbage() {
    global $img;
    if (isset($img)) {
        foreach ($img as $i) {
            if (get_resource_type($i) == 'gd') {
                imagedestroy($i);
            }
        }
        unset($img);
    }
}

register_shutdown_function("gd_garbage");

For this to work, we have to store all image resources in an array named $img. However, we shouldn’t rely on garbage collection alone to clean up GD resources, for two very important reasons:

  1. The function may fail,
  2. Leaving GD images open until the script terminates is a considerable waste of memory.

It is always recommend that you destroy your images the moment you are done with them, and let the garbage collection handle any mishaps along the way.

Thursday, November 8th, 2007 @ 04:23 PM • Next Related PostPrevious Related Post

Responses

There are no responses for this post.
Comments are open, you can write a comment below.

Respond