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: ajax, gwt, prefetching images, memory leak

Comments