Application programmers do memory management in one of two ways (I don't know of a third, tell me if you do):
  • Manual memory management, as in C. If you need an amount of memory you can't fix at compile time, you request it via a procedure call such as malloc(). When you don't need it anymore, you give it back to the operating system via an opposite operation such as free().
  • Garbage Collection, as in Java or Lisp. Again, you have to explicitly request memory, but you don't have to free it, the runtime system periodically (or when memory is needed) checks the reference structure of the program and finds objects that aren't accessible by any reference and therefore useless, and frees them for reuse.

Now what are the differences between the two systems? First of all, it's quite obvious that a GC is just plain more convenient. It spares the programmer from having to worry about freeing all the memory, and that's a Good Thing. On the downside, there is a slight performance penalty, because tracing all the references takes time. It's usually not significant for the total running time, but while it's done, the rest of the program has to pause, so it may create latency problems. Incremental garbage collection systems distribute their work more evenly over time so that latency is a smaller problem, but they impose a larger total overhead.

Then, there's the issue of memory leaks. Theoretically, a GC prevents memory leaks from ever happening. In practice, they just become rarer. The problem is that it can quite easily happen that references the programmer isn't aware of, hidden deeply in some hash table or API keeps objects from being garbage collected. Just like with manual memory management, you have a memory leak. In C, you'd probably free these objects, and the hidden reference would become a dangling pointer. If it's never accessed, that's fine. If it is, it will cause a segfault (or will it? Is it possible that a dangling pointer can become valid again? That would be Really Bad!), which makes it easy to pinpoint and fix the problem.

It's nigh impossible to find that kind of memory leak in a GC system with your bare hands. However, it's rare and relatively easy to find with a profiler.

All in all, I think the benefits of garbage collection, especially the convenience, outweight the negative points.

Log in or register to write something here or to contact authors.