Are all the variables in Go allocated on heap?

huangapple go评论82阅读模式
英文:

Are all the variables in Go allocated on heap?

问题

我是你的中文翻译助手,以下是翻译好的内容:

我刚接触Go语言,发现在函数中返回局部变量的地址是可行的。这在C语言中显然是不可能的,因为局部变量存储在栈中。

所以我想知道为什么在Go语言中这样做是可以的?在Go语言中,局部变量是存储在堆中吗?由于分配堆内存比分配栈内存要昂贵得多,这会影响性能吗?在Go语言中是否可能在栈中分配局部变量?或者实际上Go语言中是否有栈内存?

英文:

I am new to Go, and found it is OK to return the address of a local variable defined in a function. That is obviously not possible in C since local variable is in stack.

So I am just wondering why it is OK to do it in Go? In Go, the local variable is in heap? Will it affect performance since allocating heap memory is quite expensive than stack? Is it possible allocate local variable in stack in Go? Or actually is there stack memory in Go?

答案1

得分: 25

常见问题解答中,对于你的问题有一个非常明确的答案:

我如何知道变量是在堆上还是栈上分配的?

从正确性的角度来看,你不需要知道。在Go中,只要有引用指向变量,它就会存在。实现选择的存储位置对语言的语义是无关紧要的。

存储位置对编写高效程序确实有影响。在可能的情况下,Go编译器会将函数内部的局部变量分配在该函数的栈帧中。然而,如果编译器无法证明变量在函数返回后不再被引用,那么编译器必须将变量分配在垃圾回收的堆上,以避免悬空指针错误。此外,如果一个局部变量非常大,将其存储在堆上而不是栈上可能更合理。

在当前的编译器中,如果一个变量的地址被取出,那么该变量有可能被分配在堆上。然而,基本的逃逸分析会识别出一些情况,当这些变量在函数返回后不再存在时,它们可以驻留在栈上。

简而言之:你不需要关心。Go会为你处理分配问题。

英文:

There's a very clear answer to that question in the FAQ:

> 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.

TLDR: You shouldn't care. Go takes care of allocation for you.

huangapple
  • 本文由 发表于 2015年8月3日 20:10:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/31786937.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定