Golang的垃圾收集器在编译后是如何工作的?

huangapple go评论78阅读模式
英文:

How does golang's garbage collector work when compiled?

问题

当使用Go语言编译代码时,以及使用"go run"命令运行代码时,我正在尝试理解Go语言的垃圾回收器是如何工作的。我猜想"go run"命令会直接运行垃圾回收器,并处理你运行的.go文件。但是,当编译成可执行文件时,垃圾回收器是否也会被编译到二进制文件中呢?

英文:

I'm trying to understand how does golang's garbage collector work when the golang code is compiled and I guess when using go run as well. I figure go run is a little more straight forward and just runs the garbage collector along with the .go files you are running. But is the garbage collector compiled into the binaries as well when compiling to an executable?

答案1

得分: 23

编译的目标文件不包含任何垃圾回收器的"代码"。

当使用go run运行程序时,go命令会编译您的源代码,创建并启动一个可执行二进制文件在一个临时文件夹中。请参见下面的说明。

当一个应用程序被编译和链接成一个可执行二进制文件时,一个go运行时(runtime)也被包含在可执行文件中,在二进制文件启动时加载。这个运行时提供了垃圾回收器以及其他服务,如运行时反射和堆栈跟踪信息。这就是为什么一个简单的Hello World应用程序会生成一个大约2MB的可执行二进制文件的主要原因。

英文:

The compiled object files do not contain any garbage collector "code".

When a program is run with go run, the go command will compile your sources, create and start an executable binary in a temp folder. See below.

When an application is compiled and linked into an executable binary, a go runtime is also included in the executable which is loaded when the binary is started. This runtime provides the garbage collector amongst other services such as runtime reflection and stacktrace information. This is the main reason why a simple Hello World application results in like a 2 MB executable binary.

huangapple
  • 本文由 发表于 2015年8月24日 23:40:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/32186342.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定