Main Content

Cleaning up redundant objects

Archive - Originally posted on "The Horse's Mouth" - 2009-05-11 05:24:43 - Graham Ellis

In Object Oriented Design, you'll find that there's a piece of code you can add to your classes called the destructor method ... which you don't usually call explicitly in your code.

When a variable goes "out of scope" and is no longer available to your code , it is marked for destruction so that any cleanups can be done, and the memory reused.

An object can also be released / marked for destruction by an action as simple as an assignment of a different value to the same name - in this example, [PHP], $a=1; might render a big old object no longer available to your code.


You'll notice that I've said that objects are MARKED FOR destruction, rather than actually being destroyed, when no longer accessible. The actual destruction is likely to be done some time later - in bulk when the application needs to get the memory back, or is about to exit (each remaining object's destructor is always run just before the program exits). Irritating though it is that the destructors don't run straight off, it's also a huge efficiency gain for them to be run in bulk / blocks.