Garbage Collection is evil

Programming languages with built-in garbage collection (GC) is often praised as no memory leaks, less error-prone, etc but I don’t disagree with this. This article brings you some facts of GC that is never mentioned by advertisements.

GC automatically frees resources that cannot be reached but there are limitations:

  • GC does not work well with resource-limited systems. If there is only 1 MiB of memory available, the program might not get the 1025th 1 KiB object even the handle is removed after allocation each time because there is no guarantee that GC would run. Unless you can invoke the GC manually, you cannot always get programs which frequently allocate short-lived objects to run.
  • GC is complicated. It must store the reachabilities somewhere in the program. Everytime a handle is copied, the reachability database must be updated.
  • GC is selfish. It does not take care of swapping. When the physical memory is low, less often used part of memory is swapped out but each time the GC is invoked, at least the reachability database must be swapped in, causing unnecessary swapping.

To conclude, scope-based lifetime is always better than relying on the GC to free objects.

Leave a Reply

Your email address will not be published. Required fields are marked *