In my code I use an object and variables inside a function. When in that function I no longer use the object and variables I delete it:
delete myObject;
delete myVar;
Is it good practice?
Does it give speed?My JavaScript is server-side on smart.joyent.com.开发者_如何学Python
Is it good practice?
No. In fact it is disallowed in the new ECMAScript Fifth Edition ‘strict mode’:
When a delete operator occurs within strict mode code, a SyntaxError is thrown if its UnaryExpression is a direct reference to a variable, function argument, or function name (11.4.1).
If you really must, you can instead =null
the variable to free up any object it referenced for garbage collection, but it's almost never going to result in any appreciable improvement in performance.
Deleting properties of long-lived objects to free now-unused referenced objects can be a good idea, especially in the case of breaking DOM cycles to prevent memory leakage in IE. Deleting local variables inside a short-lived function isn't sensible.
I'm not sure what engine your server is using, but client-side engines typically employ garbage collection, and I wouldn't be surprised if your server environment does as well. Unless you have an extremely particular situation, most attempts of manual cleanup are probably going to be on par with (or working against) the garbage collector.
In summary, I would bet you see absolutely no difference in performance. This is a good example of micro optimization.
And also instead of using delete method, It seems that Firefox 3 allows script to invoke garbage collector with:
Components.utils.forceGC
See https://developer.mozilla.org/En/Components.utils.forceGC
Other browsers may provide similar functions too. (except IE, i don't think it provides.)
It is not generally considered necessary but in extreme, high memory situations is may be something you should look into. I do feel that its use prior to profiling and performance testing to be premature optimization.
精彩评论