Jason Rowe

Be curious! Choose your own adventure.

JS Memory Leak Tools & Tips

Javascript Closure

If you refresh the browser or go to another page and the memory doesn’t go down you probably have a closure. I just ran into a tricky situation where my closure was being caused during the successful call back of a JQuery Ajax call.

The function that was leaking looked like this:


function <span>GetData</span>(object) {

var requestObject = object.buildRequest()

$.ajax({
type: "POST",
url: object.url,
dataType: "json",
data: requestObject,
success: function(jsonResult) {
object.data = jsonResult;
object.DoStuffWithData();
}
});
}

The fix was to remove the object from being a local variable.

function GetData(object) {

var requestObject = object.buildRequest()

$.ajax({
type: “POST”,
url: object.url,
dataType: “json”,
data: requestObject,
success: function(data) {
//On Success Call Data Updater
data.id = object.Id;
DataUpdater(data);
}
});

requestObject = null;
}

function DataUpdater(data) {

//loop through Requesters Array

//must add object to global array before making DataUpdater
for (i = 0; i < Requesters.length; i++) { var temp = Requesters[i]; var requestId = temp.Id; var dataId = data.Id; //Find object with matching id if (requestId == dataId ) { temp .data = data; temp .DoStuffWithData(); } } } [/js] Drip
While tracking down this memory leak I decided to try out a memory leak tool called Drip. Unfortunately, It didn’t work in my situation. Drip actually started causing memory leaks so it made it hard to tell if I actually fixed the problem or not. I think the reason it doesn’t work is the script is recursive using setInterval.

Other Tools

Setting up IE and Firefox private bytes counters under process in Perfmon is the most reliable way to monitor JS memory leaks.

perfmon

Another common gotcha is the FireFox web developer plug-in. Turn that off if you are going to do any JS memory leak testing. It’s probably a good idea to turn off any IE plug-ins too just incase but I haven’t ran into any problems with theirs yet.

IE also has a tool bar for JS memory leaks but it didn’t work in my situation very well.

Some good pages for review:


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *