On the subject of garbage collection Python3

### Overview GC as automatic memory management in modern programming languages, focusing on two things: 1. Locate the memory resources in useless junk 2. Clear the rubbish and to make other objects out of memory to use. In Python, which maintains a counter for each object, a pointer to the record for the number of object references. Once the counter reaches 0, the object is immediately recovered, the memory space occupied by the object is released.

Reference count

We can use a simple variable references, and get a glimpse of the destruction of reference counting process.

Increase the reference count

Increasing the reference count various ways, i.e., reference to an object, the counter will +1

# 创建第一个引用
a = 3
# 用其他变量名引用
b = a
# 成为一个容器的对象
L = [1, a]
# 作为参数传递
str(a)
复制代码

Reducing the reference count

Similarly, the following are some methods to reduce the reference count

# 一个本地引用离开了其作用范围。比如`str()`函数结束时
str(a)
# 对象的别名被显式销毁 
del a   
# 对象的一个别名被复制给其他对象 
a = 'Python'
# 对象从一个窗口对象中移除 
L.remove(a)
# 窗口对象本身被销毁 
del L
复制代码

Circular reference problem

What is circular references? A and B refer to each other and no external reference to any one of A and B, although their reference count is 1, it is apparent that should be recovered.

# 对象a的引用计数为 1
a = {}
# 对象B的引用计数为 1
b = {}
# B的引用计数增1
a['b'] = b
# A的引用计数增1
b['a'] = a
# A的引用减 1,最后A对象的引用为 1
del a
# B的引用减 1, 最后B对象的引用为 1
del b
复制代码

In this case, after completion of the program execution del statement, A, B object has no references to these two objects, but each of the two objects are still referenced this subject, although the two objects had been del, and that is that we can no longer use these two objects, namely garbage objects, but they did not reduce the reference count to zero. That is based on reference counting mechanism, they will not be recovered and will always reside in memory, a memory leak. To resolve the circular object references, and the introduction of Python mark - sweep and generational recovery of two kinds of GC mechanism to solve the optimization problem.

Reproduced in: https: //juejin.im/post/5cf7cc8b518825710d2b1328

Guess you like

Origin blog.csdn.net/weixin_34320724/article/details/91424812