I have a JS function which gets called on the page every few seconds. It's an AJAX update thing.
Being a function, I declare local variables. I don't want to use closures or global variables for various reasons.
I'd never considered this, but do I need to release/clear the variables at the end of the function to release memory or will JS do this for me automatically?
To unset a variable in JavaScript, use the undefined. After that, use delete operator to completely remove it.
In contrast, JavaScript automatically allocates memory when objects are created and frees it when they are not used anymore (garbage collection). This automaticity is a potential source of confusion: it can give developers the false impression that they don't need to worry about memory management.
The JavaScript engine allocates memory when you create objects and variables in your application, and it is smart enough to clear out the memory when you no longer need the objects. Memory leaks are caused due to flaws in your logic, and they make way for poor performance in your application.
Generally, no. Variables declared with var
are local and are garbage collected when you return. If you omit the var
then the variables are global, and using the delete
keyword may be useful for global variables in some instances, but generally it's good practice to declare all variables with var
anyway to not pollute the window
namespace.
delete
can be useful when using prototype-based inheritence though, e.g:
function myclass() { this.variable = 'myvalue' ... delete this.variable // finished with this variable } var inst = new myclass()
Bear in mind that if inst
is deleted or becomes out of scope (garbage collected) all the attributes in it will be deleted as well. delete
can also be useful for deleting items from hash tables:
var d = {} d['blah'] = 'myvalue' ... delete d['blah']
There are some browser-specific garbage collection bugs. IE sometimes has problems cleaning attributes in DOM elements and closures etc for example, though many of these problems have been reduced in IE8 I believe.
Javascript has automatic garbage collection. You don't need to deallocate anything.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With