A Garbage Collection Mechanism In PHP

Garbage collection is a term for a maintenance function in a class or script that you don't want to run every time the script is run.  The main function of the script is to clean up anything that the script has used previously, but is now not important in the general running of the system and can be removed with no ill effects.  However, it is important that the garbage collection is not run every time the script is run as it may have a detrimental effect on the speed of the system.  To get around this we can use a random number generator to generate a number within a range, and use this to test if the garbage collection function should be run.  Here is the code.

if (mt_rand(1, 10) <= $garbageChance) {

The garbageChance is a variable that determines how often the garbageCollection() function is run.  With the random number being generated between 1 and 10 (inclusive) setting a low number decreases the chance of garbage collection running.

$garbageChance = 1;

For example setting the variable to 1 means that there is a 1 in 10 chance of the function being run, 5 means a 5 in 10 (or 50%) chance, and so on.  If you set the garbageChance variable to 0 the garbage collection function will never run, so that is a convenient way to turn it off completely if you have to.

Add new comment

The content of this field is kept private and will not be shown publicly.
1 + 16 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.