golang中的內存逃逸


關於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協程使用,產生逃逸


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM