关于golang的变量是定义在堆上还是栈上,官方的解释如下
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.
大概总结如下:
1、指针逃逸 - 方法返回局部变量指针,就形成变量逃逸
2、栈空间不足逃逸 - 当切片长度扩大到10000时就会逃逸,实际上当栈空间不足以存放当前对象或无法判断当前切片长时会将对象分配到堆中
3、动态类型逃逸 - 编译期间很难确定其参数的具体类型,也能产生逃逸度
4、闭包引用对象逃逸 - 原本属于局部变量,由于闭包的引用,不得不放到堆上,以致产生逃逸
5、跨协程引用对象逃逸 - 原本属于A协程的变量,通过指针传递给B协程使用,产生逃逸
网友评论