美文网首页
go中变量分配内存在堆上还是栈上的说明

go中变量分配内存在堆上还是栈上的说明

作者: 太平小小草 | 来源:发表于2018-10-12 16:46 被阅读0次

How do I know whether a variable is allocated on the heap or the stack?

From a correctness standpoint, you don't need to know. Each variable in Go exists as long as there are references to it. The storage location chosen by the implementation is irrelevant to the semantics of the language.

The storage location does have an effect on writing efficient programs. When possible, the Go compilers will allocate variables that are local to a function in that function's stack frame. However, if the compiler cannot prove that the variable is not referenced after the function returns, then the compiler must allocate the variable on the garbage-collected heap to avoid dangling pointer errors. Also, if a local variable is very large, it might make more sense to store it on the heap rather than the stack.

In the current compilers, if a variable has its address taken, that variable is a candidate for allocation on the heap. However, a basic escape analysis recognizes some cases when such variables will not live past the return from the function and can reside on the stack.

我的翻译结果:

       我怎么知道一个变量是分配在堆上还是栈上?

       正确的观点是,你不需要知道。go语言中的每一个变量,它的生命周期和引用它的周期一样长。该语言的语义和实现时选择的存储位置,是没有关系的。

       在编写高效率的程序时,存储位置的确会有影响。如果可以,go语言编译器将会分配函数的局部变量到函数的栈帧上。然而,如果编译器不能证实局部变量在函数返回后,不会再被引用,编译器将必须分配该变量到垃圾回收堆上,以避免出现悬挂指针错误。如果一个局部变量非常大,那么存储在堆上比存储在栈上也更加合理。

       在当前的编译器里,如果一个变量的地址被调用了,这个变量将会候选分配在堆上。然而,一个基本转义分析会识别一些情况。在这些情况里,变量不会存活到函数返回,这些变量将分配到栈上。

相关文章

网友评论

      本文标题:go中变量分配内存在堆上还是栈上的说明

      本文链接:https://www.haomeiwen.com/subject/vbegaftx.html