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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…