简体   繁体   中英

global variable and local variable memory consumption javascript

I want to know about more difference between global variable and local variable in javascript. I have heard one of my friend that global variable always stored in memory even function finish execution. But local variable store in memory when function start execution and removed from memory once it done with execution.

If this true how can I check memory consumption of function.

In JavaScript, variables are kept in memory as long as anything has a reference to the context in which they were created. In the case of global variables, since the global context has a reference to itself, they're always kept in memory.

That means local variables are kept in memory at least until the function they're in returns, at which point they're eligible to be reclaimed unless something still has a reference to the context in which they were created. In that case, they cannot be reclaimed, because something may still use them.

Here's an example of a local variable that can definitely be reclaimed when the function ends:

function foo(x) {
    var result = x * 2;
    return result;
}

And here's an example of a local variable that can't be reclaimed when the function returns, until or unless whatever called it releases its reference to the return value:

function makeCounter() {
    var n = 0;

    function count() {
        return n++;
    }

    return count;
}

Example use:

var c = makeCounter();
console.log(c()); // 0
console.log(c()); // 1
console.log(c()); // 2

In that case, since counter returns a function reference, and the function ( count ) has a reference to the context where n was created, n is not reclaimed as long as count exists. count is called a closure (it "closes over" the context of the call to makeCounter ).

More:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM