Monday 29 May 2017

Clearing objects from Javascript array











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];


?



Answer



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.



No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...