Sometimes I really wonder if introducing garbage collection caused more harm than good. In any non-trivial application – especially user interfaces – lifetime management of nearly all objects must be explicit to avoid dangling references and so memory leaks.
But the effects may be more subtle. For example, events in C# introduce an explicit back reference from the object providing the event and the one consuming it.
If you play careless and don’t count your event listeners, i.e. in a system, where behavior based on event listeners is attached dynamically, you may end up adding more and more event listeners to the event producers without noticing, causing memory leaks and bad performance.
Garbage collection seems – at first – to be able to solve object’s lifetime determination, but as soon you develop your software to provide a more reflective, self introspective features, you are back where you started, and may need to count.
Lesson learned: garbage collection is not about lifetime management it is about memory management. It even can’t mange the lifetime of your objects, because the time it collects is not deterministic.
But for what is it good then? As soon we introduce another level of indirection, it even comes short in terms of memory management.
The interface IDisposable and weak references are obvious signs which prove that GC has essential shortcomings. And they are not only used to manage external resources (the bad!, impure! outside world), like GC advocates might sell you…. Smells like an oversimplification, doesn’t it?
For more complex scenarios, having a destructor like mechanism is essential. For a start, I suggest to introduce some kind of “owner-lists”. Collections that own their objects and destroy their elements (in GC environments: call a destructor like method). If the owner-list also supports a destructor, this concept is nestable and can be used to build up a skeleton of “live” objects, which define the current behavior of your running program.
To move away from strict hierarchies and reference counting, I even think that a clear definition of object’s lifetime must be supported (declaratively?) in any serious next generation programming language, eradicating the need for garbage collection as a side effect.
yours
armin
All problems in computer science can be solved by another level of indirection. — Butler Lampson
But that usually will create another problem. — David Wheeler