7

What is the best way to deallocate an array of array in javascript to make sure no memory leaks will happen?

var foo = new Array();
foo[0] = new Array();
foo[0][0] = 'bar0';
foo[0][1] = 'bar1';
foo[1] = new Array();
...
  1. delete(foo)?
  2. iterate through foo, delete(foo[index]) and delete(foo)?
  3. 1 and 2 give me the same result?
  4. none?
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
andre.dias
  • 81
  • 1
  • 3

3 Answers3

9
foo = null;

should be enough for the garbage collector to get rid of the array, including all its child arrays (assuming nothing else has a reference to them). Note that it will only get rid of it when it wants to, not immediately, so don't be surprised if the browser's memory consumption doesn't drop straight away: that isn't a leak.

It potentially gets more complicated if any of those array elements contain references to DOM nodes.

NickFitz
  • 34,537
  • 8
  • 43
  • 40
  • 1
    It only gets more complicated in IE6. – SLaks Jun 08 '10 at 18:15
  • 2
    For those visiting here in 2014, please note that there is almost never reason to set something to null or try to "deallocate" it (a concept which does not exist in JS), or do anything else to get the GC to do anything. It does just fine by itself, thank you very much. –  Dec 25 '14 at 06:59
2

you can't delete variable, set it null foo = null;

.. or use a namespace object

var namespace = {};
namespace.foo = [];
delete namespace.foo;
Lauri
  • 1,298
  • 11
  • 13
0

I think Array.splice also might do the trick for you. Its an alternative to using delete on each index.

Ref: https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/Splice

You can also combine it with Array.forEach like this:

foo.forEach(function(element,ind,arr){
 arr.splice(ind,1);  //emptying the array
});
foo = null; //remove ref to empty array

If you just use the forEach part, you will empty the foo array. I think internally the splice method removes a reference so you will be good removing elements this way.The last line then removes the reference to the empty array that is left.

Not very sure on this but worth some research.

Rajat
  • 32,970
  • 17
  • 67
  • 87