I have a JavaScript closure which I keep recreating throughout the life time of my web application (single full-ajax page).
I would like to know if it’s creating a memory leak.
Here is an example JSFIDDLE
The code in question:
function CreateLinks() {
var ul = $("<ul></ul>").appendTo('div#links');
for (var i in myLinks) {
var li = $('<li>' + myLinks[i].name + '</li>').appendTo(ul);
//closure starts here
(function (value) {
li.click(function (e) {
$('div#info').append('<label>' + value + '</label><br />');
RecreateLinks();
});
})(myLinks[i].value);
}
}
You should be okay IF you make sure that you avoid binding multiple
clickhandlers in theRecreateLinks()function; this can be done by explicitly unbinding existing ones, removing the DOM nodes or making sure that you won’t be adding multipleclickhandlers.Browsers are getting better at memory allocation strategies, but you shouldn’t assume too much. If memory usage is a big concern, try to avoid creating too many closures of which you’re not sure they will get garbage collected. One such approach is to use
.data()to store your value object and then use a generic click handler instead of a closure.Profiling JavaScript is not so simple; Chrome does have a Profile tool that can monitor CPU and data performance. This can give you a pretty good gauge on the expected memory consumption, but Chrome is not all browsers, keep that in mind.