Language - Garbage Collector (GC)


Language that have a garbage collector allows you to create as many variable (objects) as you want and you don't have to worry about destroying them. Their runtime environment deletes objects when it determines that they are no longer being used. This process is called garbage collection.

How does the garbage collector know that a variable’s storage can be reclaimed?

The basic idea is that every package-level variable, and every local variable of each currently active function, can potentially be the start or root of a path to the variable in question, following pointers and other kinds of references that ultimately lead to the variable. If no such path exists, the variable has become unreachable, so it can no longer affect the rest of the computation.

Example in Go

  • When g returns, the variable *y becomes unreachable and can be recycled.
func g() {
    y := new( int)
    *y = 1
  • conversely, x must be heap-allocated because it is still reachable from the variable global after f has returned, despite being declared as a local variable; we say x escapes from f.
var global *int 

func f() { 
        var x int  x = 1
        global = &x 

Documentation / Reference

Powered by ComboStrap