Agile Ajax

GWT Image.prefetch memory leak and suggestions for improvement

In answering a question over at the GWT google group, I came across what I think is a misfeature with Image.prefetch. The code for prefetch looks like this:

public static void prefetch(String url) {    Element img = DOM.createImg();    DOM.setImgSrc(img, url);    prefetchImages.put(url, img);} 

The reason that the images are stored in a static hash is because in some browsers, under some circumstances, the image DOM element is garbage collected before it is loaded. That's great. But there is a problem here: these prefetched images are now not garbage collected at all. If you prefetch 1024 images of 1M each, you will have 1G of images in your browser. In some browsers, prefetching the same image several times will apparently create lots of copies, each chewing up more memory. (I haven't seen this in IE7 and FF2 in my brief testing.)

So, what to do? For starters, I'd suggest testing to see if we've already loaded an image. Second, I'd add the ability to unfetch or release a resource:

public static void prefetch(String url) {    if (!prefetchImages.containsKey(url)) {        Element img = DOM.createImg();        DOM.setImgSrc(img, url);        prefetchImages.put(url, img);    }}

public static void release(String url) {    prefetchImages.remove(url);}

You could do something with an onLoad event or automatically kick out earliest image from a FIFO queue when prefetching a new image, but I'm not sure that gives you enough control. Anyhow, the above gives you enough control to be useful.

Technorati Tags: , , ,

Topics:

Comments: 1 so far

  1. Good point. I had noticed the same thing. I still don’t like the fact that I must explicitly call the release. I think the framework should be smart enough to GC the images in the prefetchImages HashMap

    Comment by Harold Campbell, Saturday, August 23, 2008 @ 10:26 pm

Leave a comment

Powered by WP Hashcash

About Pathfinder

  • We design and build extraordinary applications for companies looking to make the next great idea a reality.
  • learn more

Topics

WordPress

Comments about this site: info@pathf.com