Python in , Mainly garbage collection through reference counting
Each object maintains a ob_ref Field , Used to record the number of times the object is currently referenced , Whenever a new reference points to the object , Its reference count ob_ref Add 1, Count every time a reference to this object fails ob_ref reduce 1, Once the reference count of an object is 0, The object is immediately recycled , The memory space occupied by the object will be freed . Its disadvantage is that it requires additional space to maintain reference counts , This problem is secondary to , But the main problem is that it can't solve the problem of objects “ Circular reference ”, therefore , There are also many languages, such as Java There is no garbage collection mechanism using this algorithm .
To put it bluntly, the number of object references increases or decreases
The citation counting method has its obvious advantages , If efficient 、 The implementation logic is simple 、 Real time , Once the reference count of an object is set to zero , Memory is released directly .
Increased the burden of space , Each object needs to allocate a separate space to count the reference count , At the same time, its maintenance will also increase the burden .
Circular reference cannot be implemented
Mark removal algorithm is a kind of garbage collection algorithm based on trace collection technology . It is divided into two stages
The first stage : Marking stage ,GC Will mark all active objects
The second stage : Put those unmarked objects 【 Inactive objects 】 To recycle .
Generational recycling is a way of exchanging space for time ,Python The memory is divided into different sets according to the lifetime of the object , Each set is called a generation ,Python Divide memory into 3“ generation ”, They are the young generation ( The first 0 generation )、 Middle age ( The first 1 generation )、 Old age ( The first 2 generation ), They correspond to 3 A linked list , Their garbage collection frequency and the survival time of objects increase and decrease . The newly created objects will be assigned to the younger generation , When the total number of young generation linked lists reaches the upper limit ,Python The garbage collection mechanism will be triggered , Recycle the objects that can be recycled , And objects that won't be recycled will be moved to the middle ages , And so on , The object of the old generation is the one who has the longest life , Even in the whole life cycle of the system . meanwhile , Generational recycling is based on marker removal technology . Generation recycling is also used as Python The auxiliary garbage collection technology of the company deals with those container objects
Reference resources :
https://foofish.net/python-gc.html
https://zhuanlan.zhihu.com/p/83251959