Memory release from local variable in JavaScript - 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?

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.

Variables are released once they are out of scope, in your case, the local variables that are declared inside your function will be automatically freed by js garbage collector, you don't have to worry about them.

Related

Deleting variable from memory node.JS

I know, that, for example, c++ has something like delete variable and it will be deleted from the memory. Is there something like this in JS.
For example, I have var canSendRequest = true; and after some operations I want to delete it totally from the memory. As I read, delete canSendRequest will not work properly, but I did not manage to find a properly working way. Does someone know, how to do that?
Since JS is garbage collected, you don't have direct control over the release of memory.
You just have to wait for the runtime to free the memory, which it will if there are no permanent references to it via the global object or a permanently existing closure. In those cases, you need to eliminate such references to the variable so that it qualifies to be freed.
If you're saying you want to eliminate the identifier itself from the scope, you definitely can't unless it was a global that was set as a property of the global object, not using proper variable declaration syntax.
Var is Hoisting type use let or const. like var g_a = 1; //create with var, g_a is a variable delete g_a; //return false console.log(g_a); //g_a is still 1
now try with let and const

Is calling new class on same variable cause a memory leak?

I have a function like this
function runThis(){
var class = new aClass();
// using the class variable
}
if i run this function several times, can this cause a memory leak or that new class automatically destroyed?
The new class gets destroyed when you go out of the scope (out of runThis in this case) or when you re-assign the variable. The memory gets cleaned only when a new cycle of the garbage collector is ran, like in Java.
To learn more about garbage collection you can read here.
This is not much different than Java or other high-level programming languages, but it still presents some caveats.
Note that var preserves the variable hoisting. Maybe you'd prefer using const or let.

Does javascript Garbage Collector dispose global variables?

I'm confused about this since I've seen several different comments. I'm reading a javascript book where it mentions that setting global variables to null is good practice (assuming there are no other references) and the GC reclaims memory for this variable on it's next sweep. I've seen other comments that say global variables are never disposed by the GC.
Also when programming javascript in a OOP structure, what happens if I have something like this (where game is in the global context):
var game = {};
game.level = 0;
game.hero = new hero();
//do stuff
game.hero = null;
Since hero lives inside an object which is stored in game, which is in a global context, If I set for instance hero to null, would this be disposed by the GC?
Global variables are never disposed of by the GC in the sense that a global variable will still exist. Setting it to null will allow the memory that it references to be collected, however.
E.g.
Before:
global -> {nothingness}
After:
global -> var a -> object { foo: "bar" }
Set a to null:
global -> var a -> null
Here, the memory used by the object will be eligible for collection. The variable a still exists though, and it simply references null.
The statement that global variables are never collected is slightly misleading. It might be more accurate to say that any memory that is traceable back to the global context is not currently eligible for collection.
In answer to your question, yes - the hero object will be eligible for collection, because its indirect connection to the global context has been severed.

Object Orientated Javascript / Variable declarations / Performance

So I have a rather large object orientated javascript class, with about 120 functions (a lot of getters and setters). Some of these functions have variables that are basically constants.
What I'm wondering, is should I declare these variables in a global scope of the object, so every time the function is run it doesn't have to re-declare the variable?
An example function is below. this.displayContacts is run several times (and will always run within the object), so in this case, there's no point declaring the 'codes' object inside the function?
function orderObject() {
this.displayContacts = function() {
var codes = {'02':'02','03':'03','07':'07','08':'08'};
// do something with codes
};
}
So, would this be better, performance wise?
function orderObject() {
var codes = {'02':'02','03':'03','07':'07','08':'08'};
this.displayContacts = function() {
// do something with codes.
};
}
My other concern is that if I end up with a lot of global variables/objects inside the main orderObject, will that be MORE of a performance hit than simply re-declaring the variables each time?
absolutely.
function MyClass() {
this.somevar = ''; // instance scoped variable
};
MyClass.CODES = {'02':'02'...}; // 'Class' scoped variable; one instance for all objects
MyClass.prototype.instanceMethod = function(){
// 'this' refers to the object *instance*
// it can still use MyClass.CODES, but can also account for variables local to the class
}
CONSTANT is 'static' so to speak, in java-talk. If your codes are global to the class (and the rest of your application), you will save a lot of overhead this way -- only define the object once. Note that you can have 'static' class-level methods as well, for those cases where the function doesn't need to operate on variables specific to an instance of the class.
Unless your app is really beefy, performance optimization probably wont make it noticeably faster. But that doesn't mean that OO design is not worth-while -- if you are going to use javascript in an object oriented way, its not too hard and never a bad idea to use good OO principals.
I would say that if you have something that you are using in multiple places that it should become a property of your object so that it doesn't have to be redeclared each time. It would also help make the maintenance of the object easier if that constant has to change. Then you are changing it only in one place and not having to hunt down all the locations where you used it.
Don't repeat yourself.
Garbage collection in JavaScript depends on the browser, and most modern browsers handle it pretty well. If you go ahead and make these global, you might see a slight performance increase simply because it's not executing that line of code every time. However, I can't imagine any significant increase in performance by making these static properties on the class, but if they don't change, then it would make more sense.

JavaScript garbage collection when variable goes out of scope

Does JavaScript support garbage collection?
For example, if I use:
function sayHello (name){
var myName = name;
alert(myName);
}
do I need to use "delete" to delete the myName variable or I just ignore it?
no.
delete is used to remove properties from objects, not for memory management.
JavaScript supports garbage collection. In this case, since you explicitly declare the variable within the function, it will (1) go out of scope when the function exits and be collected sometime after that, and (2) cannot be the target of delete (per reference linked below).
Where delete may be useful is if you declare variables implicitly, which puts them in global scope:
function foo()
{
x = "foo"; /* x is in global scope */
delete x;
}
However, it's a bad practice to define variables implicitly, so always use var and you won't have to care about delete.
For more information, see: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/delete_Operator
Ignore it - after the sayHello function completes, myName falls out-of-scope and gets gc'ed.
You don't need to do anything Ted, no need to delete this variable.
Refer: http://www.codingforums.com/archive/index.php/t-157637.html
As others mentioned, when the function exits then your variable falls out of scope, as it's scope is just within the function, so the gc can then clean it up.
But, it is possible for that variable to be referenced by something outside the function, then it won't be gc'ed for a while, if ever, as it is still has a reference to it.
You may want to read up on scoping in javascript:
http://www.webdotdev.com/nvd/content/view/1340/
With closures you can create memory leaks, which may be the problem you are trying to deal with, and is related to the problem I had mentioned:
http://www.jibbering.com/faq/faq_notes/closures.html

Categories

Resources