Skip to content

Golang 内存管理初探

golang内存管理(上篇)

tcmalloc的介绍

一个Goroutine部分,分为G,M,P三个部分组成

  • G Goroutine执行的上下文环境

  • M 操作系统线程

  • P Processer. 调度器

逃逸分析

package main
import ()
func foo() *int {  
  var x int
  return &x
}
func bar() int {
  x := new(int)
  *x = 1
  return *x
}
func main() {}

关于执行的命令如下:

$ go run -gcflags '-m -l' escape.go
./escape.go:6: moved to heap: x
./escape.go:7: &x escape to heap
./escape.go:11: bar new(int) does not escape

注意上面的代码,foo()的x是分配到堆上,而bar()中的x是分配到栈上