Stack versus heap allocation in Go stayed fuzzy until I read the articles in the references at the end. Here is a condensed version.
What the Go FAQ says
How do I know whether a variable is allocated on the heap or the stack?
From a correctness standpoint, you do not 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 affect efficient code. When possible, the Go compilers allocate variables that are local to a function in that function’s stack frame. If the compiler cannot prove that the variable is not referenced after the function returns, it must allocate on the garbage-collected heap to avoid dangling pointer errors. If a local variable is very large, the heap may be a better choice than the stack.
In current compilers, taking the address of a variable makes heap allocation likely. Escape analysis can still keep some of those variables on the stack when they clearly do not outlive the function.
关于变量分配在堆和栈的问题一直不太了解,直到看了附录几篇文章,有了一个初步的认识。
先看官网怎么说
go变量分配到堆还是栈
从正确的角度来看,你不需要知道。Go中的每个变量只要有引用就会存在。实现选择的存储位置与语言的语义无关。
存储位置对编写高效程序有影响。如果可能的话,Go编译器将为该函数的栈帧(stack frame)中分配本地变量。但是,如果编译器无法证明变量在函数返回后未被引用,则编译器必须在存在垃圾回收的堆(garbage-collected heap)上分配变量以避免指针错误。另外,如果局部变量非常大,将其存储在堆而不是栈上可能更有意义。
在当前的编译器中,如果一个变量的地址被占用,那么该变量就成为堆中的一个候选对象。但是,一些基本的逃逸分析可以识别出某些情况下,这些变量不会在函数的返回后还存在,就可以驻留在栈中。
Read More
Read More