BeFruit

Tuesday, June 5, 2007

JavaScript Closures and memory leaks

You sometimes use techniques unconsciously, and you discover it later when trying to locate a bug. Closures in JavaScript is one of those. If you create functions dynamically, you often create a closure:

function formatMoney(sFormat){
    return function(iAmount){
        return sFormat.replace('[amount]',iAmount);
    }
}
var formatEuro=formatMoney('[amount] €');
var formatDollar=formatMoney('$[amount]');
alert(formatEuro(12)+' - 'formatDollar(23));

displays "12 € - $23".

You can notice that the sFormat variable, declared outside the function definition is still present when the function formatEuro is actually called. This is possible because JavaScript creates an object with the dynamically created function and its context with the local variables.

Why does this provoke memory leaks? Well, it shouldn't, as JavaScript has a garbage collector, and the objects created on the fly are freed when needed. But some browsers (IE?) are worse than others on that aspect, and circular references, particularly between JavaScript and DOM objects remain locked.

Taking care of memory leaks becomes more important as we create Ajax applications that do not jump from page to page, and do not give an occasion to the browser to completely flush its working memory. Badly designed Ajax applications can increase the memory used by your browser to a point that locks your computer completely.

A good article at ibm.com explains what are the common patterns leading to memory leaks, and a few solutions to avoid them.

Labels: ,

0 Comments:

Post a Comment



<$I18N$LinksToThisPost>:

Create a Link

<< Home