闭包中的变量存储在哪里 - 堆栈还是堆? [英] Where are variables in a closure stored - stack or heap?

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

问题描述

与以下代码类似:

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

当foo退出(或说,返回)时,我们知道变量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天全站免登陆