views:

152

answers:

4

I have to maintain a JavaScript object with some 30-40 properties, which I update every few seconds. I have read that there is no such thing as "freeing" memory in JavaScript, and the browser automatically garbage collects unused memory.

My question is: is it enough to set the object itself to null, or do I need to set all its properties to null and then set it to null?

var obj = [];
obj[prop1] = "123";
obj[prop2] = "456"; 
//...and so on...

// now to release the obj, is it enough if I just did:
obj = null; 
A: 

Setting properties to null is unnecessary. Any values stored in properties will be freed by the garbage collector. As an alternative, the delete operator will likely force immediate destruction:

delete obj;
outis
`delete` doesn't force object destruction - it removes properties from objects; also, local variables can't be deleted; doing so even is a syntax error in strict-mode ECMAScript 5
Christoph
A: 

An object can only be collected if it is no longer reachable. You can achieve this by setting all local variables which reference the object to null (any other value would do as well) and deleting (or overwriting) any properties of other objects which reference it.

Deleting the object's own properties or explicitly setting them to null won't gain you anything in this regard: The references of the object won't be considered 'alive' if itself isn't.

Christoph
+1  A: 

The only times (I can think of) where you would need to set items to null are a few cases where the DOM is involved.

For example, if you have a node with several child nodes each with an onclick handler defined by anonymous functions, then setting each onclick to null would be a good idea (to avoid unintentional circular references).

<div id="delete_me">
  <span></span>
  <span></span>
</div>

var theDiv = document.getElementById('delete_me');
for (var i=0; i < theDiv.childNodes.length; i++) {
  theDiv.childNodes[i].onclick = function () {
    // stuff
  };
}

// Later...
// Delete stuff.
var divToDelete = document.getElementById('delete_me');

// Remove all the onclicks
for (var i=0; i < theDiv.childNodes.length; i++) {
  theDiv.childNodes[i].onclick = null;
}

// Delete the div
divToDelete.parentNode.removeChild(divToDelete);
ntownsend
+1  A: 

Variables are not garbage collected until there is at least one reference to them. However, be aware that global variables are visible from "everywhere" and may sometimes not get garbage collected, because they are still visible from somewhere.

For instance, you have

var a = {"testkey": "testval"};

var b = jQuery.ajax({
   url:"http://somewhere",
   method: "GET",
   onSuccess: function() {
      //this function is called asynchronously, moments later,
      //but as "a" is defined in the enclosing variable scope,
      //you can access it from here
      alert(a.testkey);
   }
});

Therefore, I would consent to setting value to null after you are done with your object.

naivists