Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to deallocate an array of array in javascript

Tags:

javascript

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?
like image 727
andre.dias Avatar asked Jun 08 '10 17:06

andre.dias


2 Answers

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.

like image 131
NickFitz Avatar answered Sep 21 '22 15:09

NickFitz


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

.. or use a namespace object

var namespace = {};
namespace.foo = [];
delete namespace.foo;
like image 31
Lauri Avatar answered Sep 23 '22 15:09

Lauri