user3559463 user3559463 - 1 year ago 80
Javascript Question

Closure memory leak patterns in JavaScript

Which of following JavaScript snippets will leak memory?

snippet #1:

function foo(obj)
{
var obj2 = {};
$('#something').click(function() { alert(obj.id); } );
}


snippet #2:

function foo(obj)
{
var obj2 = {}
$('#something').click(function() { alert('obj was not used.'); } );
}


snippet #3:

function foo(obj)
{
var obj2= {id: 1}
bar(function() { alert(obj2.id); } );
}

function bar(func)
{
var obj3 = {};
func();
}


and which variables won't be collected by Garbage Collector?
How to fix leaks?

Answer Source

As given, none of those will create memory leaks.

Leaks are held by not releasing memory -- everything there gets released.

By the way, none of the code you are showing uses closures.

Now, here are a handful of ways that "leaks" can be created.

// Simple leak -- an array that never lets go of memory
var arrayThatNeverShrinks = [];
function doleak() {
  var s = "1234567890";
  arrayThatNeverShrinks.push(s);
  window.setTimeout(doleak, 500);
}
//start if off
doleak();


// This function leaks because bigVar is used -- and kept -- 
// inside of the anonymous function inside.
    //Another leak, using closures
    var leakingFunction = (function() {
      var bigVar = "1234567890";
      return function() {
        alert("Hi there");
        var keepBigVar = bigVar;
      }
    }());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download