Python GC uses reference counts (reference counting) primarily to track and recycle garbage.
On the basis of reference counting, through "mark-clear" (Mark and sweep) to solve the problem that the container object may produce circular reference, through "generational recovery" (generation collection) to improve garbage collection efficiency by means of space-time-changing.
1 Reference count
Pyobject are the necessary content for each object, which ob_refcnt
is the reference count. When an object has a new reference, it is ob_refcnt
incremented, and when the object referencing it is deleted, it is ob_refcnt
reduced. The object's life ends when the reference count is 0 o'clock.
Advantages:
- Simple
- Real-time sex
Disadvantages:
- Maintain reference count consumption resources
- Circular references
2 Mark-Clear mechanism
The basic idea is to allocate on demand, wait until there is no free memory from the register and the reference on the stack to start, traverse the object as a node, the reference as the edge of the graph, all the objects can be accessed to mark, and then sweep the memory space, all unmarked objects released.
3 Generational Technology
The whole idea of generational recycling is that all memory blocks in the system are divided into different sets according to their survival time, each set becomes a "generation", and the garbage collection frequency decreases with the increase of the survival time of "generation", and the survival time is usually measured by several garbage collection.
Python By default defines a collection of three generations of objects, the larger the number of indexes, the longer the object survives.
For example: When some memory block M has survived after 3 garbage collection cleaning, we have divided the memory block m into a set a, and the newly allocated memory is divided into set B. When garbage collection begins to work, most cases are garbage collected only for collection B, and collection A is garbage collected for quite a long time, which makes the garbage collection mechanism need to deal with less memory, the efficiency naturally increased. In this process, some blocks of memory in set B are transferred to set a because of their long lifetime, and of course there is some garbage in the collection A, which is delayed because of this generational mechanism.
**python garbage collection mechanism