简体   繁体   English

全局变量和局部变量内存消耗javascript

[英]global variable and local variable memory consumption javascript

I want to know about more difference between global variable and local variable in javascript. 我想知道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. 在JavaScript中,只要任何东西都引用了创建变量的上下文,变量就会保留在内存中。 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. 在这种情况下,由于counter返回一个函数的参考,并且函数( count )具有其中上下文的引用n被创建, n只要不回收count存在。 count is called a closure (it "closes over" the context of the call to makeCounter ). count被称为闭包 (它“关闭”对makeCounter的调用的上下文)。

More: 更多:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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