Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

performance - How to quickly clear a JavaScript Object?

With a JavaScript Array, I can reset it to an empty state with a single assignment:

array.length = 0;

This makes the Array "appear" empty and ready to reuse, and as far as I understand is a single "operation" - that is, constant time.

Is there a similar way to clear a JS Object? I know I can iterate its fields deleting them:

for (var prop in obj) { if (obj.hasOwnProperty(prop)) { delete obj[prop]; } }

but this has linear complexity.

I can also just throw the object away and create a new one:

obj = {};

But "promiscuous" creation of new objects leads to problems with Garbage Collection on IE6. (As described here)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Well, at the risk of making things too easy...

for (var member in myObject) delete myObject[member];

...would seem to be pretty effective in cleaning the object in one line of code with a minimum of scary brackets. All members will be truly deleted instead of left as garbage.

Obviously if you want to delete the object itself, you'll still have to do a separate delete() for that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.6k users

...