go - gc Go 是如何处理堆分配的?

标签 go

gc Go(特别是go1.11)是否预先分配了一 block 内存并在每次分配时从中获取(如JVM),或者它在每次创建变量时分配,它是内核调用(malloc) ?

如果每次分配一次内核调用,那将使创建变量变得昂贵。如何在堆栈/堆上强制分配?

最佳答案

这在很多地方都有介绍,比如 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.


Go 的内存分配针对其需求进行了仔细优化,例如 custom malloc .我怀疑您正在努力解决的潜在问题/问题略有不同-最好问一下。如果这只是探索/好奇,则您必须使问题更加具体。

关于go - gc Go 是如何处理堆分配的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54152719/

相关文章:

windows - 在 Windows Server 2008 上构建时为 "not a valid Win32 Application"

go - 从 golang 中的 fixed64 protobuf 字段读取 int64

提供静态文件时出现 golang 错误

go - 向现有的http处理函数添加上下文

go - GoClipse v0.91 可以开放定义吗?

go - 一元与流基准

go - 使用子包/子包构建包结构

go - 如何使用代码生成器生成自定义资源定义的代码

linux - Golang 中的 slice 导致空白终端和困惑的线程

regex - Golang regex lookarround 不支持错误解析 regexp : invalid or unsupported Perl syntax: `(?!`