What are some of the standard issues or coding patterns in jQuery which lead to memory leaks?


I have seen a number of questions related to the ajax() call or jsonp or DOM removal on StackOverflow. Most of the jQuery memory leak questions are focussed on specific issues or browsers and it would be nice to have a listing of the standard memory leak patterns in jQuery.

Here are some related questions on SO:

  • Why does jQuery leak memory so badly?
  • Simple jQuery Ajax call leaks memory in Internet Explorer
  • Memory leak involving jQuery Ajax requests

Resources on the web:

  • How to attach objects and data to DOM with jQuery.data to avoid memory leak issues
  • Memory leak patterns in JavaScript

Solution 1:

From what I understand, memory management in javascript is accomplished by reference counting - while a reference to an object still exists, it will not be deallocated. This means that creating a memory leak in a single page application is trivial, and can trip up those of use coming from a java background. This is not specific to JQuery. Take the following code for example:

function MyObject = function(){
   var _this = this;
   this.count = 0;
   this.getAndIncrement = function(){
       _this.count++;
       return _this.count;
   }
}

for(var i = 0; i < 10000; i++){
    var obj = new MyObject();
    obj.getAndIncrement();
}

It will look normal until you look at memory usage. Instances of MyObject are never deallocated while the page is active, due to the "_this" pointer (increase the max value of i to see it more dramatically.). (In older versions of IE they were never deallocated until the program exits.) Since javascript objects may be shared between frames (I don't recommend trying this as it is seriously temperamental.), there are cases where even in a modern browser javascript objects can hang around a lot longer than they are meant to.

In the context of jquery, references are often stored to save the overhead of dom searching - for example:

function run(){
    var domObjects = $(".myClass");
    domObjects.click(function(){
        domObjects.addClass(".myOtherClass");
    });
}

This code will hold on to domObject (and all its contents) forever, because of the reference to it in the callback function.

If the writers of jquery have missed instances like this internally, then the library itself will leak, but more often it is the client code.

The second example can be fixed by explicitly clearing the pointer when it is no longer required:

function run(){
    var domObjects = $(".myClass");
    domObjects.click(function(){
        if(domObjects){
            domObjects.addClass(".myOtherClass");
            domObjects = null;
        }
    });
}

or doing the lookup again:

function run(){
    $(".myClass").click(function(){
        $(".myClass").addClass(".myOtherClass");
    });
}

A good rule of thumb is to be careful where you define your callback functions, and avoid too much nesting where possible.

Edit: As was pointed out in the comments by Erik, you could also use the this pointer to avoid the unnescessary dom lookup:

function run(){
    $(".myClass").click(function(){
        $(this).addClass(".myOtherClass");
    });
}

Solution 2:

I'll contribute one anti-pattern here, which is the "mid-chain reference" leak.

One of jQuery's strengths is its chaining API, which lets you continue to change, filter, and manipulate the elements:

$(".message").addClass("unread").find(".author").addClass("noob");

At the end of that chain you have a jQuery object with all the ".message .author" elements, but that object refers back to and object with the original ".message" elements. You can get to them via the .end() method and do something to them:

 $(".message")
   .find(".author")
     .addClass("prolific")
   .end()
   .addClass("unread");

Now when used this way there are no problems with leaks. However, if you assign the result of a chain to a variable that has a long life, the back-references to earlier sets stay around and cannot be garbage collected until the variable goes out of scope. If that variable is global, the references never go out of scope.

So for example, let's say you read on some 2008 blog post that $("a").find("b") was "more efficient" than $("a b") (even though its not worthy of even thinking about such a micro-optimization). You decide you need a page-wide global to hold a list of authors so you do this:

authors = $(".message").find(".author");

Now you do have a jQuery object with the list of authors, but it also refers back to a jQuery object that is the full list of messages. You probably will never use it or even know it's there, and it's taking up memory.

Note that leaks can only occur with the methods that select new elements from an existing set, such as .find, .filter, .children etc. The docs indicate when a new set is returned. Simply using a chaining API doesn't cause a leak if the chain has simple non-filtering methods like .css, so this is okay:

authors = $(".message .author").addClass("prolific");