3 ms·
>> we have a giant for loop that iterates over all of memory over and over and over > How is that not how garbage collectors work?... I'm assuming we're talkin
by altfredd 7y ago
>> we have a giant for loop that iterates over all of memory over and over and over
> How is that not how garbage collectors work?... I'm assuming we're talking about a standard, generational mark-and-sweep gc
GCs do not scan "all memory", but small fraction of memory. In case of generational GC the scanned fraction of memory is (usually) limited to single generation. Even without generational approach scanning heap itself is frequently avoided in favor of scanning separate data structure with highly compressed representation of object set.
GCs do not generally iterate over memory just because they can. They either reclaim space for new allocations, move things around to reduce fragmentation or fire periodically in response to increased allocation rate. If your program does not make allocations, it may never incur a GC at all.
The grandparent comment makes it sound like garbage collection is a simple effort, conducted solely by distinct GC code ("giant for loop"). This is often not the case: for example, JVM may generate additional memory barriers in any code, that uses references (exact nature and purpose of memory barriers depends on GC being used [1]). Augmenting the code with those barriers allows GC to operate more efficiently and quickly: achieve smaller pauses, scan less memory, collect memory for some threads without disturbing others.
[1]: https://shipilev.net/jvm/diy-gc/#_barriers https://shipilev.net/jvm/diy-gc/#_barriers