Python garbage Collection
Python garbage collection uses reference counts primarily to track and recycle garbage. On the basis of reference counting, through "mark-clear" to solve the problem of circular reference that can be produced by container object, the garbage collection efficiency is improved by the method of "generational recycle".
1. Reference counting
Pyobject are the necessary content for each object, where ob_refcnt is counted as a reference. When an object has a new reference, its ob_refcnt is incremented, and when the object referencing it is deleted, its ob_refcnt is reduced, and the reference count is 0 o'clock, and the object's life object ends.
Reference count Advantages: simple, real-time disadvantage: maintain reference count consumption resources, circular reference
2. Mark-Clear mechanism
The basic idea is to allocate on demand, wait until there is no leisure memory, from the register and the reference on the program stack to traverse, the object is a node, a reference to the image of the graph, all the objects can be accessed tagged, and then sweep the memory space, all unmarked objects released.
3, sub-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.
Example:
When some memory blocks M has survived after 3 garbage collection cleaning, we row 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