Junior — Middle
Can you describe how the garbage collector works in Go?
sobes.tech AI
Answer from AI
In the Go language, the garbage collector (GC) is implemented as a concurrent, multithreaded, low-latency system. Its task is to automatically free memory that is no longer used by the program.
Main principles of operation:
-
Three-phase process:
- Mark: GC traverses all roots (variables, stack, global objects) and marks all reachable objects.
- Sweep: All objects not marked as reachable are considered garbage and are freed.
- Minimal pauses: GC aims to minimize pauses in program execution by performing most work in parallel with main threads.
-
Generational approach: Go GC does not divide objects into generations but is optimized for quick detection of unused objects.
-
Trigger: GC is triggered when the allocated memory reaches a certain threshold relative to already allocated memory.
Example: a developer does not manually manage memory but simply creates objects, and GC automatically frees unused ones.
func main() {
data := make([]byte, 1024*1024) // allocate 1MB
_ = data
// When data is no longer used, GC will automatically free the memory
}
Thus, the garbage collector in Go simplifies memory management and reduces the likelihood of leaks.