ChatGPT解决这个技术问题 Extra ChatGPT

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

This question already has answers here: Closed 12 years ago.

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?

@jeffreyveon: the answer can be found in the responses to the first question Crescent Fresh links to, but I'll summarize here before you go read that: you can't "force" the browser to garbage collect anything; delete merely removes a property from an object (vs. giving a property the value of null). Assuming you have no external references to your object, it'll be garbage collected regardless of whether or not you empty or delete the properties first.

D
DeBraid

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

JavaScript is such a peculiar language. One thing I find strange is how the variable in for loops don't go out of scope after the loop. In your code you didn't need to redefine "key", because "key" is already defined. Very strange I tell you. It's frustrating to have complete control. I actually never heard of this delete keyword before. I always null out variables for the reason that I may have accidentally defined it somewhere else and I don't know what the parser (or a user using IE!). Thanks for sharing your knowledge.
@pqsk What you are mentioning about for loops is an instance of variable hoisting. Its actually pretty cool once you wrap your head around it! jsfiddle.net/a4awzxd7/1
@catalyst294 Well, you can say it's cool, but it is also the main reason why there is so much messy javascript code around. This can also lead to unexpected behaviour if the person making the code does not fully understand the lack of scoping.
M
Matt DiMeo

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@


G
Gabriel McAdams

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.


"Each JavaScript engine has its own way of handling that" - Not completely accurate, according to this, all modern browsers use a variation of "Mark-and-sweep" algorithm, since 2012: developer.mozilla.org/en-US/docs/Web/JavaScript/…
@NoBugs I think that's what he meant. "their own way of handling" === "a variation of"...