views:

95

answers:

1

I just read this question and the accepted answer: http://stackoverflow.com/questions/864516/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 load of my scripts. So I went off to test some things. The following is an example of an obect that deletes itself after invoking a method. The example includes a jquery domready event as well.

(function ($, someglobal) {
    $(function () {
        var scoped_object = function () {
            var init, a_method, and_another;
            a_method    = function() { /* do stuff */ };
            and_another = function() { /* do some other stuff*/ };
            init        = function() { a_method(); and_another(); };
        };
        delete new scoped_object().init();
    });
})($, someglobal);

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?

+5  A: 

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 delete operator 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 how delete works!!.

They even recommend using delete on variable references, and that is not possible -only possible for variables declared in Eval Code-, because the var statement declares the variable as non-deletable ({DontDelete} in ECMAScript 3, or [[Configurable]] = false in ECMAScript 5) properties of the Variable Object -objects that form the scope chain-.

Moreover, attempting to delete a reference to an identifier that is bound to an environment record - an identifier declared with a VariableDeclaration, FunctionDeclaration or from a function's FormalParameterList-, causes a SyntaxError exception on the new ECMAScript 5th Edition under Strict Mode.

I would recommend you to read the following article about delete:

CMS
Thats awesome. Thank you!
Stephen
+1 for the link to the article by Kangax. Awesome article!
Rajat