import matplotlib.pyplot as plt
import random, psutil
def png(x, y) -> None:
(fig, axs) = plt.subplots(1, 1, figsize=(17, 5))
axs.plot(x, y)
if __name__ == '__main__':
while True: # RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`).
png(random.randint(1, 10), random.randint(1, 10))
print('memory % used:', psutil.virtual_memory()[2])
出去:
如果在使用链表等循环结构时不使用弱引用,Python 可能会泄漏内存。尽管循环垃圾收集器应该跟踪这些对象,但在实践中,如果没有正确处理循环对象,它们可以保持很长时间。例如,如果你从上面的链表中删除头部,那么整个 body 将在内存中保持未释放,并且将无法访问它。
简单的例子:
结论
如果您删除了weakref.ref,则输出
在这个例子中,使用了弱引用,当对象被删除时,所有的节点都会被删除。如果不使用它们,则所有节点将保持存在。对它们的访问将永远消失。因此,在使用循环对象时,建议使用弱引用。