Python: garbage collection

Python GC mainly used reference count (reference counting) to track and garbage. On the basis of the reference count, by - loop "flag clear" (mark and sweep) container object to resolve references may arise problems and improve the efficiency of garbage collection by "generational recovery" (generation collection) In the method of space for time.
1 reference count

PyObject is each object must have content, which ob_refcnt is used as the reference count. When a new object is referenced, it will increase the ob_refcnt, when it is referenced object is deleted, its ob_refcnt will reduce the reference count is 0, the object of life is over.

advantage:

简单
实时性

Disadvantages:

维护引用计数消耗资源
循环引用

2 mark - sweep mechanism

The basic idea is to demand assignment, time until no free memory references from the program stack and registers starting node traversed to object, by reference to FIG side configuration, all objects accessible to the marked tag, then sweep memory space again, not all marked objects released.
3 points generation technology

Generational recovered whole idea is: all system memory block is divided into different sets according to their survival, each set becomes a "generation", with an increase in the frequency of garbage collection "generation" of the survival time reduced survival time is usually after several use garbage collection to measure.

Python defines a default set of three generations of objects, the larger the index number, the longer the survival time of the object.

Example: When the M memory blocks after certain elapsed washed three times garbage collection still alive, we will draw to a memory block M to the set A, and the newly allocated memory are divided into set B to. When the garbage collection to work, in most cases only a collection of B garbage collection, and the collection A garbage collection to be separated for a long period of time before, which makes up less memory garbage collection need to be addressed, efficiency naturally increased. In this process, some memory blocks in set B because long survival time will be transferred to the set A, of course, in fact, set A, there are some garbage, because the garbage which this mechanism generational It is delayed.

Guess you like

Origin blog.csdn.net/weixin_44523387/article/details/91897025