garbage-collectionheap-memorymemory-fragmentation

Copying Garbage Collector


How does a copying garbage collector avoid memory fragmentation? Also, what consequences for heap-space use?

From my understanding, a copying garbage collector, copies all reachable objects from the heap into another section of the heap. All objects that have been left behind are no longer needed and thus removed.

If this is a correct understanding, how does this avoid memory fragmentation?

This process must use a lot of heap-space, because it will have duplicates of all items it copied, right?


Solution

  • If this is a correct understanding, how does this avoid memory fragmentation?

    Because when you copy the objects to the "new heap", you stick them right next to each other without leaving any gaps.

    This process must use a lot of heap-space, because it will have duplicates of all items it copied, right?

    Only during the collection process. After you've done that, all the "originals" are deallocated and that space is freed up again.

    Additionally, garbage collectors like this are often "generational" - copying garbage collection is used on short-lived objects, with longer-lived objects being treated differently. This helps ease the space issue, as well as making collections take less time.