Book Image

Learning jQuery : Better Interaction Design and Web Development with Simple JavaScript Techniques

Book Image

Learning jQuery : Better Interaction Design and Web Development with Simple JavaScript Techniques

Overview of this book

Table of Contents (18 chapters)
Learning jQuery
Credits
About the Authors
About the Reviewers
Preface

Memory Leak Hazards


JavaScript manages its memory using a technique known as garbage collection. This is in contrast to low-level languages like C, which require programmers to explicitly reserve blocks of memory and free them when they are no longer being used. Other languages such as Objective-C assist the programmer by implementing a reference counting system, which allows the user to note how many pieces of the program are using a particular piece of memory so it can be cleaned up when no longer used. JavaScript is a high-level language, on the other hand, and generally takes care of this bookkeeping behind the scenes.

Whenever a new memory-resident item such as an object or function comes into being in JavaScript code, a chunk of memory is set aside for this item. As the object gets passed around to functions and assigned to variables, more pieces of code begin to point to the object. JavaScript keeps track of these pointers, and when the last one is gone, the memory taken by the object is released. Consider a chain of pointers:

Here object A has a property that points to B, and B has a property that points to C. Even if object A here is the only one that is a variable in the current scope, all three objects must remain in memory because of the pointers to them. When A goes out of scope, however (such as at the end of the function it was declared in), then it can be released by the garbage collector. Now B has nothing pointing to it, so can be released, and finally C can be released as well.

More complicated arrangements of references can be harder to deal with:

Now we’ve added a property to object C that refers back to B. In this case, when A is released, B still has a pointer to it from C. This reference loop needs to be handled specially by JavaScript, which must notice that the entire loop is isolated from the variables that are in scope.

Accidental Reference Loops

Closures can cause reference loops to be inadvertently created. Since functions are objects that must be kept in memory, any variables they have in their closing environment are also kept in memory:

function outerFun() {
  var outerVar = {};
  function innerFun() {
    alert(outerVar);
  };
  outerVar.innerFun = innerFun;
  return innerFun;
};

Here an object called innerFun is created, and referenced from within the inner function innerFun(). Then a property of outerVar that points to innerFun() is created, and innerFun() is returned. This creates a closure on innerFun() that refers to innerFun, which in turn refers back to innerFun(). But the loop can be more insidious than this:

function outerFun() {
  var outerVar = {};
  function innerFun() {
    alert('hello');
  };
  outerVar.innerFun = innerFun;
  return innerFun;
};

Here we’ve changed innerFun() so that it no longer refers to outerVar. However, this does not break the loop. Even though outerVar is never referred to from innerFun(), it is still in innerFun()’s closing environment. All variables in the scope of outerFun() are implicitly referred to by innerFun() due to the closure. So, closures make it easy to accidentally create these loops.

The Internet Explorer Memory Leak Problem

All of this is generally not an issue because JavaScript is able to detect these loops and clean them up when they become orphaned. Internet Explorer, however, has difficulty handling one particular class of reference loops. When a loop contains both DOM elements and regular JavaScript objects, IE cannot release either one because they are handled by different memory managers. These loops are never freed until the browser is closed, which can eat up a great deal of memory over time. A common cause of such a loop is a simple event handler:

$(document).ready(function() {
  var div = document.getElementById('foo');
  div.onclick = function() {
    alert('hello');
  }
});

When the click handler is assigned, this creates a closure with div in the closing environment. But div now contains a reference back to the closure, and the resulting loop can’t be released by Internet Explorer even when we navigate away from the page.

The Good News

Now let’s write the same code, but using normal jQuery constructs:

$(document).ready(function() {
  var $div = $('#foo');
  $div.click(function() {
    alert('hello');
  });
});

Even though a closure is still created causing the same kind of loop as before, we do not get an IE memory leak from this code. Fortunately, jQuery is aware of the potential for leaks, and manually releases all of the event handlers that it assigns. As long as we faithfully adhere to using jQuery event binding methods for our handlers, we need not fear leaks caused by this particular common idiom.

This doesn’t mean we’re completely out of the woods; we must continue to take care when we’re performing other tasks with DOM elements. Attaching JavaScript objects to DOM elements can still cause memory leaks in Internet Explorer; jQuery just helps make this situation far less prevalent.