Python 垃圾回收(GC)机制

变量是指向一个对象的指针;有n个变量指向某一个对象,那该对象的引用计数则为n,又称该对象有n个引用.引用没有了,就自动回收了.

查看全局有哪些引用变量

globals()

查看局部有那些引用变量

locals()

查看变量的引用次数.增加引用的方式有:赋值运算,参数传递,将对象附加到容器对象中(list.append(list) 当一个list对象添加自己为元素,这种递归,Python的分代回收机制会处理)

sys.getrefcount(va_name)

在python中对象分为可变对象和不可变对象。不可变对象包括int, float, complex, strings, bytes, tuple, range 和 frozenset;可变对象包括list, dict, bytearray和 set。循环引用仅存在于container对象(比如,list, dict, classes, tuples),python垃圾回收算法主要追踪可变对象及不可变对象tuple。如果tuple, dict包含的元素都是不可变对象,那么回收算法可以不对该对象进行追踪。


https://lifediary.com.cn/2024/01/22/hello-world/
Author
张梁
Posted on
2024年1月22日
Licensed under