views:

305

answers:

3

Possible Duplicate:
Deleting Objects in JavaScript

I have a JS object having a large number of properties. If I want to force the browser to garbage collect this object, do I need to set each of these properties as null or do I need to use the delete operator? What's the difference between the two?

A: 

There is no way to force garbage collection at a specific time in JavaScript. Each JavaScript engine has its own way of handling that.

What you can do, though, is make sure your objects aren't being referenced anywhere. Setting them to null or deleting them are actually doing the same thing (delete never deletes the object - it only removes a reference to it). When garbage collection does run, it checks to see if there are any references to a given object - then, if not, it removes it from memory. This is where memory leaks occur (a JavaScript object is referencing a DOM object, and vice-versa).

Make sure you remove all references and you'll be fine.

Gabriel McAdams
+2  A: 

There is no way to force garbage collection in JavaScript, and you don't really need to. x.y = null; and delete x.y; both eliminate x's reference to the former value of y. The value will be garbage collected when necessary.

The only time I can think of where you would prefer delete is if you were going to enumerate over the properties of x. If you null out a property, it is still considered 'set' on the object and will be enumerated. Consider the following:

var foo = { 'a': 1, 'b': 2, 'c': 3 };

console.log('Deleted a.');
delete foo.a
for (var key in foo)
  console.log(key + ': ' + foo[key]);

console.log('Nulled out b.');
foo['b'] = null;
for (var key in foo)
  console.log(key + ': ' + foo[key]);

This code will produce the following output:

Deleted a.
b: 2
c: 3
Nulled out b.
b: null
c: 3
Annabelle
Care to explain the downvote?
Annabelle
A: 

Javascript objects properties are typically implemented with a hashtable. Setting to null leaves the key in the hashtable pointing to a null value, while delete eliminates both the key and the value.

The main observable difference between the two is that if you iterate over the keys with a for..in loop, deleting keys results in fewer entries seen by the iteration.

I would suggest preferring deletion in general, unless you are going to be repeatedly setting and clearing the same keys, which would argue for leaving the hash table structure in place. However, any performance difference between the two techniques is going to be immeasurably small in any typical case.

-m@

Matt DiMeo