哪里的变量在闭包存储,堆栈或堆? [英] Where is the variable in the closure stored, stack or heap?

查看:712
本文介绍了哪里的变量在闭包存储,堆栈或堆?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如下列代码:

  var foo = function(){
var a = 1; // closure var
return function(){// closure fun
console.log(a);
}
};
var bar = foo();

当foo退出(或说,返回)时,我们知道变量a不会被销毁,保留在内存(这就是为什么闭包工作)。所以我的问题是变量a存储,堆栈或堆在哪里?

解决方案



堆栈用于在调用函数时分隔/隔离作用域。当函数返回堆栈帧(激活记录)被弹出调用堆栈,从而释放使用的内存,允许下一个函数调用重用该RAM的堆栈帧。



一个闭包做的是,而不是实际释放该堆栈帧,如果堆栈帧中有任何其他任何引用的对象/变量,那么它保留该堆栈帧供将来使用。



大多数语言通过将堆栈实现为链表或哈希表而不是平面数组来实现。这样,堆栈可以在运行时重新排序,并且不受物理内存布局的限制。



所以。考虑到这一点,答案是闭包中的变量存储在堆栈和堆中。取决于你的观点。



从语言的角度来看,它绝对是堆栈。因为这是理论上的闭包 - 修改的堆栈。



从机器语言或底层C /汇编代码的角度来看,链表的想法堆栈是废话。因此,高级语言必须使用堆来实现其堆栈。



所以变量在堆栈中,但堆栈可能位于堆中。 / p>

这当然取决于你的编程语言的实现。但上面的描述对大多数javascript解释器(当然是我见过的所有)有效。


Like the following codes:

var foo = function() {
    var a = 1; // closure var
    return function() { // closure fun
        console.log(a);
    }
};
var bar = foo();

When foo exits(or say, returns), we know that the variable a will not be destroyed and remains in memory(that's why closure works). So my problem is where does the the variable a store, stack or heap?

解决方案

A closure is just an evolution of the concept of the stack.

The stack is used to separate/isolate scope when functions are called. When a function returns the stack frame (activation record) is popped off the call stack thus freeing the used memory allowing the next function call to reuse that RAM for its stack frame.

What a closure does is that instead of actually freeing that stack frame, if there's any object/variable in that stack frame that's referenced by anything else then it keeps that stack frame for future use.

Most languages implement this by implementing the stack as a linked list or hash table instead of a flat array. That way, the stack can be re-ordered at runtime and is not constrained by physical memory layout.

So. With this in mind, the answer is that variables in a closure are stored in the stack and heap. Depending on your point of view.

From the point of view of the language, it's definitely the stack. Since that's what closures are in theory - a modified stack.

From the point of view of the machine language or underlying C/assembly code, the idea of a linked-list stack is nonsense. Therefore the higher level language must be using the heap to implement its "stack".

So the variable is in the stack but that stack is probably located in the heap.

This of course depends on the implementation of your programming language. But the above description is valid for most javascript interpreters (certainly all the ones I've seen).

这篇关于哪里的变量在闭包存储,堆栈或堆?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆