Grav v1.14.0

GC

import "std/core" (included in import "std") · namespace std.core

Control over the cycle collector. Grav frees objects by reference counting: an object goes the moment its last reference does. Objects that refer to each other in a cycle keep each other alive, so a cycle collector looks for groups that are only reachable from each other and frees them. It runs on its own as candidates accumulate; GC.collect() runs it now.

grav
import "std"

class Node {
    public next: Node
    constructor() { self.next = null }
}

fn main() {
    for (i in 0..3) {
        let a = new Node()
        let b = new Node()
        a.next = b
        b.next = a           // a cycle
    }
    print("candidates: ${GC.pending() > 0}")
    print("freed: ${GC.collect()}")
    print("candidates after: ${GC.pending()}")
}
Output
candidates: true
freed: 6
candidates after: 0

The collector only runs while no other Thread or async task is using objects; collect() returns 0 at other times. To avoid cycles altogether, mark back-references weak. See Memory.

API

class GC

Static members

  • static fn collect() -> int — Collects unreachable cycles now. Returns the number of objects freed (0 while other threads or async tasks are running).
  • static fn pending() -> int — Objects currently recorded as possible members of a cycle.

Edit this page on GitHub