python(63): dict: del/pop不释放内存

Python中的字典,只有不再使用的时候才会释放对应的内存。在使用 pop 或者 delete 删除字典中的item(或者说entry)后,为了保证hash table 探测链的完整,那个被删除的entry只是被标记成了空,并没有真正被删除掉,所以该字典的内存占用没有得到释放。这是为了避免多度重建hash table。

释放内存

那如何释放字典的内存?现已知的方案是创建或者拷贝一个旧字典再覆盖掉新字典。具体示例如下:

复制代码
import sys
import gc
import copy
a = {}
print("init empty dict memory size={} bytes".format(sys.getsizeof(a)))

for i in range(10**6):
    a[i] = i
print("after set value, dict memory size={} bytes".format(sys.getsizeof(a)))

for i in range(10**6):
    del a[i]
    # a.pop(i)

print("after del, dict memory size={} bytes".format(sys.getsizeof(a)))
a_new = dict(a)
print("after init a new one, dict memory size={} bytes".format(sys.getsizeof(a_new)))
b = copy.copy(a)
print("after copy a new one, dict memory size={} bytes".format(sys.getsizeof(b)))
c = copy.deepcopy(a)
print("after deepcopy a new one, dict memory size={} bytes".format(sys.getsizeof(c)))

运行结果如下:

复制代码
init empty dict memory size=240 bytes
after set value, dict memory size=41943144 bytes
after del, dict memory size=41943144 bytes
after init a new one, dict memory size=240 bytes
after copy a new one, dict memory size=240 bytes
after deepcopy a new one, dict memory size=240 bytes

参考文档;

Python应用专题 | 11:如何释放字典的内存占用?-阿里云开发者社区

相关推荐
apocelipes14 小时前
常用编程语言和库的正则表达式性能对比
c语言·c++·python·性能优化·golang·开发工具和环境
用户83562907805116 小时前
使用 Python 在 PDF 中创建与管理书签
后端·python
MeixianAgent20 小时前
Python 回测数据入口怎么验?历史 K 线入库前先做 5 个检查
后端·python
咕白m6251 天前
用 Python 实现一键批量查找与替换 Excel 数据
后端·python
SelectDB2 天前
Apache Doris Python UDF:让 SQL 直接调用 Python 生态,支撑 Agent 时代复杂业务逻辑
大数据·数据库·python
荣码2 天前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python
金銀銅鐵2 天前
[Python] 基于欧几里得算法,实现分数约分计算器
python·数学
Lyn_Li3 天前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
小九九的爸爸3 天前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学3 天前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员