3

Possible Duplicate:
how to empty an array in JavaScript
Best way to deallocate an array of array in javascript

I have an array of objects:

var arr = [complexObj1, complexObj2];

If I want to clear the array and ensure that there is no memory leak, will the following do it?

arr.length = 0;

Or do I need to iterate through my array and call something like:

complexObj.release(); or
arr[0] = null; or 
delete arr[0];

?

Community
  • 1
  • 1
Charlotte Tan
  • 2,452
  • 2
  • 20
  • 24
  • yup, I actually read the question of [how to empty an array in Javascript](http://stackoverflow.com/questions/1232040/how-to-empty-an-array-in-javascript) already, which is why I wrote arr.length = 0 as a possible solution. I'm asking whether it will actually trigger JS garbage collection if the objects are not simple objects like strings and ints – Charlotte Tan Oct 08 '12 at 11:41

4 Answers4

2

If the array consists of simple objects without references to other methods or DOM elements then all of the above solutions are enough.

If, however, the array contains objects that in turn holds references to event handlers that you have attached to DOM elements the object will not be destroyed when you clear the array.

var Complex = function(nodeId){
   this.node=document.getElementById(nodeId);
   this.handler=function(e){alert('wohooo'};

   this.node.addEventListener('click', this.handler);
}

var myArray = [new Complex('buttonOne'), new Complex('buttonTwo')];

If you now 'reset' the array using myArray = []. The array will be cleaned up but the objects still hold a node and a live event handler which will trigger when the buttons are clicked, meaning the object can't be removed from memory. You just lost a reference to it by removing from the array.

Your first thought was correct in that you should somehow 'destroy' the complex object and remove any references it holds.

Complex.prototype.release = function() {
    this.node.removeEventListener('click',this.handler);
    delete this.handler;
    delete this.node

}

You now loop through the array and call release on the objects to remove the event listeners from the node.

This is a simple example of what I think people usually miss. It doesn't have to be event handlers either but can be anything that is referenced outside of the complex object.

batzkoo
  • 1,275
  • 1
  • 10
  • 10
1

Just re-initialize the array:

arr = [];
elclanrs
  • 92,861
  • 21
  • 134
  • 171
Codesen
  • 7,724
  • 5
  • 29
  • 31
0

You need to do just

arr = null
Anshu
  • 7,783
  • 5
  • 31
  • 41
0

Something like

var t = myArray;
delete myArray;
//or
myArray = null;
shox
  • 1,150
  • 5
  • 18
  • 32