memory-management - Go 中的变量是否都分配在堆上?

标签 memory-management go heap-memory

我是 Go 的新手,发现返回函数中定义的局部变量的地址是可以的。这在 C 中显然是不可能的,因为局部变量在堆栈中。

所以我只是想知道为什么在 Go 中可以这样做?在 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:你不应该关心。 Go 会为您处理分配。

关于memory-management - Go 中的变量是否都分配在堆上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31786937/

相关文章:

ios - 异步或静态调用如何实现强大的保留周期?

java - Activity 占用大量内存,如何减少?

go - 如何在运行 go mod download 时强制使用特定的软件包版本?

go - 如何将字符串从接口(interface)转换为golang中的[]字符串?

c++ - 您可以删除在堆上创建并由函数返回的数组吗?

java - 监控 Java 堆使用情况

scala - 意外的 Scala 集合内存行为

iphone - 改变self的指针

Golang 命令在终端中工作但不与 exec 包一起工作

由于堆中存在大量 JSP/HTML 内容而导致 Java OutOfMemory