FF6 .. More to combat memory leaks :)

by Developer @ pebbl.co.uk on Sunday, 10 July 2011

If you count yourself as an advanced JavaScripter, then you will have definitely come across these three terms:

  1. Garbage Collection
  2. Closures
  3. Memory Leaks

If not, then you might need to go back to guru school - or at least, stop being so damn flukey with your implementations. In today's scripting world, Memory Leaks seem to be an inevitable side-affect of development getting more rapid, throw-away and high-level. It also seems to be a side-effect of the copy & paste / lazy generation - but then a lot can be blamed on them ;)

However, even the most conscientious coder can propagate memory leaks with their code. For instance, they might not fully understand each JavaScript engine that their work will be deployed on (highly likely) or they may accidently get lost in too many nested closures. Either way the outcome is the same, memory usage creep. The good news is that FireFox 6 has a plan that can help, in the form of Weak References.

Weak, Strong... Reference?

If you haven't heard of weak references before, then it would make sense that you don't refer to your normal variable references as strong... but that is precisely what they are. The difference between weak and strong references is all to do with garbage collection.

A strong reference to any variable, array or object (i shall call these items) will be counted by the garbage collector, only items that have no strong references are ever deleted/garbage collected. Memory Leaks occur when strong references are left pointing to their original items, even when the code that created them has finished. This is because the garbage collector (GC) assumes the referenced items are still in use and so doesn't delete the item and free up the memory.

Weak references however do not increment the garbage collector's reference count, and so when the GC comes to clean up, even if there have been many weak references left lying about the place, the original item will still be deleted. This does mean that an item that is only held by weak references might just suddenly disappear, so you need to be aware of what you want to keep.

WeakMap

FireFox's idea to support weak references is in the form of the WeakMap Object/API.

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/WeakMap

By the looks of things WeakMap allows you to store data without the strong reference, it's experimental at the moment, but it should mean that you can store anything that you don't mind loosing. You would normally use this by having one strong reference and all other access to this item as weak, then when you delete the original strong reference the item will become viable for garbage collection.

So no more worrying about data being remembered long after your script has forgotten what it was that it was supposed to be doing.

Leave your comment