Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use delete vs setting elements to null in JavaScript? [duplicate]

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?

like image 497
jeffreyveon Avatar asked Dec 22 '09 17:12

jeffreyveon


People also ask

Why we should not use Delete in JavaScript?

The delete operator shouldn't be used on predefined JavaScript object properties like window , Math , and Date objects. It can crash your application.

Does delete return value?

Explanation: The delete operator doesn't return any value. Its function is to delete the memory allocated for an object.

Is delete bad practice JavaScript?

No, it's not considered bad practice.


2 Answers

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.

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

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 
like image 98
Annabelle Avatar answered Sep 20 '22 12:09

Annabelle


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@

like image 41
Matt DiMeo Avatar answered Sep 20 '22 12:09

Matt DiMeo