[Python] garbage collection

GC as automatic memory management in a programming language, nothing more than to do two things: find unwanted objects in memory, clearing the target memory space vacated. General talk GC general we think is Java, but there are also Python, Python matter used in reference count based, marking clear and generational recovery supplement.

Reference count:

  Everything in Python is an object, if the object is a reference to another object, then it ob_ref ​​count is incremented, decremented when referring to failure, when the count of 0 when the object is immediately recovered. But this is also a problem, that is, if the object is a circular reference, using this method will not automatically lead to GC, so memory leaks.

Clear labeling:

  Clear labeling is divided into two phases, one phase mark, this time on all of GC "active objects" branded mark, the second stage is not marked "non-active objects" for recycling. But between the object reference, how do I distinguish active inactive objects?

  Between objects by reference together, constitute a departure from the root object to the FIG., The edges along with a traverse the object, the object is marked as reachable active objects, such as from black specks, can 1,2,3 up, unreachable 4,5, 2,3 will be marked, 4,5 recovered GC. The root object is a global variable, call stacks, registers, some of the processing vessel The algorithm objects, such as list, dict, tuple, instance, etc., because the string values ​​and objects unlikely to cause a circular reference problem, but also to use a doubly linked list Python these container objects organized.

 

Generational recovery:

  This mode of operation is similar to Java, the memory is divided into different sets based on the survival time of the object, divided into the young generation, in time, the old times, it corresponds to the three lists.

  The newly created object will be allocated in the young generation, the young generation of the list when the total number reaches the upper limit, this time will trigger a GC, the recovery can be recycled objects, objects can not be recycled in the year, and so on, the old era the oldest objects survive when the objects.

  Further, generational recovery is based on the clear marking, thus also the processing container object. ,

 

reference:

https://zhuanlan.zhihu.com/p/62282961

 https://github.com/kenwoodjw/python_interview_question#50python%E7%9A%84%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86%E6%9C%BA%E5%88%B6%E5%8F%8A%E8%B0%83%E4%BC%98%E6%89%8B%E6%AE%B5

 

Guess you like

Origin www.cnblogs.com/guangluwutu/p/12383266.html