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

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语言编译器将会分配函数的局部变量到函数的栈帧上。然而,如果编译器不能证实局部变量在函数返回后,不会再被引用,编译器将必须分配该变量到垃圾回收堆上,以避免出现悬挂指针错误。如果一个局部变量非常大,那么存储在堆上比存储在栈上也更加合理。

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 13,937评论 0 38
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,458评论 0 10
  • 偶然看到一个帖子提到了这个市郊的铁路桥。知道的人说这是郑州老东北环联络线,曾连接陇海京广两大干线,但已经废弃很久了...
    信马归风阅读 2,311评论 3 8
  • 网络主播廖勋钦生活?当今社会,绝大部分人和网络打交道,是为了获取信息或网上购物,但也有不少人将网络作为一种生财之道...
    此寡百都鼐chuil阅读 279评论 0 0