I just read this question and the accepted answer: What is JavaScript garbage collection?
In the answer, Noldorin referenced some guidelines from Apple. Here is the part I’m concerned with:
Use delete statements. Whenever you create an object using a new statement, pair it with a delete statement. This ensures that all of the memory associated with the object, including its property name, is available for garbage collection.
I’m always taking time to keep up-to-speed on best practices, especially if I can reduce the memory footprint of my scripts. So I went off to test some things. If I understand correctly, the following is an example of an object that deletes itself after invoking a method.
var thing = function () {
var a_method, and_another;
a_method = function() { /* do stuff */ };
and_another = function() { /* do some other stuff*/ };
this.init = function() { a_method(); and_another(); };
};
delete new thing().init();
Usually I’ll wrap everything in a self invoking function and pass in my globals just like above. Everything is the same as I would normally do it, the only difference being that I added the delete right before the new.
The code works either way.
So the question is: Am I doing anything here? Is there some kind of benefit to deleting a reference to an object that only exists inside a function scope? Or am I just making things look confusing?
First of all the statement
delete new scoped_object().init();is not really doing anything, you should better take care about what variables remain in-closure or if you have circular references, which are the most common source of memory leaks.The
deleteoperator is meant to be used to delete object properties, and it is really misunderstood, the answer you quote from @Noldorin quotes some text of the Apple JavaScript “Best Practices”, but they don’t have a clue about howdeleteworks!!.They even recommend using
deleteon variable references, and that is not possible -only possible for variables declared in Eval Code-, because thevarstatement declares the variable as non-deletable ({DontDelete}in ECMAScript 3, or[[Configurable]] = falsein ECMAScript 5) properties of the Variable Object -objects that form the scope chain-.Moreover, attempting to
deletea reference to an identifier that is bound to an environment record – an identifier declared with aVariableDeclaration,FunctionDeclarationor from a function’sFormalParameterList-, causes aSyntaxErrorexception on the new ECMAScript 5th Edition under Strict Mode.I would recommend you to read the following article about
delete:delete