Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory release from local variable in JavaScript

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?

like image 623
Bob Avatar asked Apr 21 '10 09:04

Bob


People also ask

How do you release a variable in JavaScript?

To unset a variable in JavaScript, use the undefined. After that, use delete operator to completely remove it.

How are variables allocated memory in JavaScript?

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.

Why do we need to free up memory in JavaScript?

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.


2 Answers

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.

like image 184
cryo Avatar answered Oct 04 '22 18:10

cryo


Javascript has automatic garbage collection. You don't need to deallocate anything.

like image 32
Max Shawabkeh Avatar answered Oct 04 '22 20:10

Max Shawabkeh