Javascript delete statement - javascript

Q: I am trying to work out why there is a delete statement in this code?
My assumption is foo will be dereferenced once statement has finished executing therefore would be no need to explicitly do it.
(function () {
var foo = globalObject;
foo.bar = function () {
//code here
}
delete foo;
}());
What is going on here?

See this article on when To and Not To use the delete operator.
This does not appear to be a proper use.
Local variables cannot be deleted as they are marked internally with the DontDelete attribute. There are occasions when you might want to clear a local variable (if you want to release any memory used by it and the scope may survive indefinitely in a closure), but you don't use the delete operator for this purpose - you can just set it to null.
In normal functions that don't create closures, any local variables will simply be garbage collected when the function completes and if there are no other references to their data in other code, that data will be freed by the garbage collector.
The only time you need to worry about clearing references to data is when you have a scope that will exist for a long duration of time (closure or global) and you no longer need that data and it's useful to free up its memory usage.
FYI, the most common use of the delete operator is to remove a property from an object as in:
var foo = {x: 1, y: 2};
delete foo.x;

Related

Is important to set 'var = null' in the end of lexical scope?

I was reading this post that clarified almost everything about scopes, leaving only this doubt:
If lexical scopes generate a new environment on each run and store their information, in an environment where code runs frequently, you need to declare var_of_scope = null at the end of the scope to free memory or JavaScript recognizes this automatically if not are there elements that refer to the environment?
No, that is almost never necessary.
Javascript uses garbage collection. When no values in any scope reference a value stored in memory, it is removed during the next run of garbage collector.
In the situation you describe:
function foo() {
let data = "some data here"
// do stuff with data
data = null
}
Setting the null here is not helpful. It does remove all references the previous value of data, but since the scope will end when the function ends, all local variables will be discarded along with it anyway.
In fact, this would prevent you from using the const keyword, which is a very very good thing to use. All your variables should be const by default, and you should change them to let only if you really need to assign them after initialization.
This is better:
function foo() {
const data = "some data here"
// do stuff with data
}
In general, you just don't have to worry about this. It's not easy to leak memory in javascript like it is in a language like C. It's possible but as long your following most best practices you'll probably be fine.

Whether 'var' allocates new memory when re-accessed or overwrites it?

function Foo(){
var someObj = {
s: 'string'
}
console.log(someObj.s);
}
Foo(); // first call
Foo(); // second call
Will the memory where the someObj points to are overwritten or will a new one be allocated? If new memory will be allocated, what happens with someObj created at first call, will garbage collector erase it? And should I make a definition of someObj outside the function to reduce the number of memory operations?
A new someObj will be created on each call of Foo. You can check this by returning the object and seeing if the new one is equal:
function Foo(){
var someObj = {
s: 'string'
};
return someObj;
}
console.log(Foo() === Foo());
They're not the same - the location in memory that the first someObj points to is not the same as the location in memory that the second someObj points to. If you continually called Foo without leaving time for the GC to run, you would eventually run out of memory.
If the object is not returned, then after Foo runs, nothing else can reference the someObj, so it will be GC'd shortly.
If you want to prevent multiple someObjs from being created, yes, feel free to define someObj outside of Foo.
If you want someObj to only be referenceable inside of Foo while also creating only one such object, then turn Foo into an IIFE:
const Foo = (() => {
var someObj = {
s: 'string'
};
return () => {
console.log(someObj.s);
};
})();
Foo();
As far as I'm concerned that's nothing I would really care when writing js. It's up to the compiler (V8 or whatever is compiling your code) to do necessary optimisations.
But:
Will the memory where the someObj points to are overwritten or will a new one be allocated?
I says it's allocated every time function is called. Or, in other words, you can treat it as new variable all the time.
what happens with someObj created at first call, will garbage collector erase it
Yes, when function is called and exits, this reference is marked as trash, which should be cleaned up by GC when GC kicks in.
And should I make a definition of someObj outside the function to reduce the number of memory operations?
From my knowledge about V8 and similar, as longs as the type is always the same, there are some built-in techniques that would make this optimisation.
However, in general I cannot imagine how often this would have to be called, that you'd need any optimisation in this kind of code.
This question sounds like either some academic problem (which I probably can't help much) or some attempt of premature optimisations.
As a side note. Code is primarily for other humans. It should be readable for them first.

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.

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?
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.

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