Introduction to the garbage collection mechanism by php reference counters

  • 2020-05-24 05:15:07
  • OfStack

PHP has a very simple garbage collector that will actually garbage collect objects that are no longer in the memory range (scope). The internal way of garbage collection is to use a reference counter, so when the counter reaches 0 (meaning that no reference to the object is available), the object is garbage collected and removed from memory.

Every computer language has its own automatic garbage collection mechanism that lets programmers not worry too much about memory allocation. php is no exception, but in object-oriented programming (OOP) programming, some objects need to be explicitly destroyed. Prevent program execution from running out of memory.

1. PHP garbage collection mechanism (Garbage Collector for short GC)

In PHP, when no variables point to this object, it becomes garbage. PHP will destroy it in memory; This is PHP's GC garbage handling mechanism to prevent memory leaks.

When one PHP thread ends, all currently occupied memory space is destroyed and all objects in the current program are destroyed at the same time. The GC process 1 normally starts with one SESSION per file. The purpose of gc is to automatically destroy and delete session files after they expire.

2. __destruct /unset

S () destructor, which is to be performed while the garbage object is being collected.
unset destroys the variable pointing to the object, not the object.

3. Session GC

Due to the working mechanism of PHP, it does not have one daemon thread to periodically scan Session information and judge whether it is invalid. When a valid request occurs, PHP will decide whether to enable one GC based on the global variables session.gc_probability and session.gc_divisor. session.gc_probability =1, session.gc_divisor =100 that means there is a 1% chance that GC will be started (that is, only 1 gc out of 100 requests will be started with a request out of 100).

The job of GC is to scan all Session information, subtract the last modified time of session from the current time, compare it with the session.gc_maxlifetime parameter, and delete session if the lifetime exceeds gc_maxlifetime(24 minutes by default).
However, if you have multiple sites on your Web server,GC's handling of session may have unexpected results when you have multiple sites. The reason for this is that GC does not distinguish between the session of different sites when it works.

So what's the solution at this point?

1. Modify session.save_path, or use session_save_path() to save session at each site to a dedicated directory,
2. The startup rate of GC is provided. Naturally, if the startup rate of GC is increased, the performance of the system will be correspondingly reduced, so it is not recommended.
3. Determine the current lifetime of session in the code, and delete it with session_destroy()

Related articles: