引用计数机制
Python 通过引用计数管理内存,当引用计数归零时立即回收。
import sys
a = []
print(sys.getrefcount(a)) # 2 (变量 + getrefcount 参数)循环引用与 GC
循环引用(如两个对象相互引用)会导致引用计数无法归零,由标记-清除机制处理。
class Node:
def __init__(self):
self.ref = None
a = Node()
b = Node()
a.ref = b
b.ref = a
# a 和 b 形成循环,引用计数为 2,GC 会处理分代回收
Python 将对象分为三代(0,1,2),新对象在 0 代,存活越久越不容易被回收。
import gc
gc.get_threshold() # (700, 10, 10)内存泄漏排查
使用 tracemalloc:
import tracemalloc
tracemalloc.start()
# ... 运行代码 ...
snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics('lineno')
print(top_stats[0])slots 优化
限制实例属性,减少内存占用。
class Point:
__slots__ = ('x', 'y')
def __init__(self, x, y):
self.x = x
self.y = y理解内存管理有助于编写高性能、长运行的服务。
