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?
As long as an object is being referenced, the JVM considers it alive. Once an object is no longer referenced and therefore is not reachable by the application code, the garbage collector removes it and reclaims the unused memory.
In Java, garbage collection is the process of managing memory, automatically. It finds the unused objects (that are no longer used by the program) and delete or remove them to free up the memory. The garbage collection mechanism uses several GC algorithms. The most popular algorithm that is used is Mark and Sweep.
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects. To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically.
gc() method: System class contain static method gc() for requesting JVM to run Garbage Collector. Using Runtime. getRuntime(). gc() method: Runtime class allows the application to interface with the JVM in which the application is running.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With