json.dump(x,f) is much slower than f.write(json.dumps(x))
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 77.2k
- 派生
- 36k
- PR 合并指标
- PR 指标待抓取
描述
Bug report
Bug description:
Experimentally I measured a huge performance improvement when I switched my code from
json.dump(x, f, **)
to
f.write(json.dumps(x, **))
Method
I essentially wrote the same contents to different files sequentially and measured the total amount of time taken. The json contents had 1, 300, and 400 entries per level, and 1, 5, and 6 levels of depth. There's quite a level of variance here but this wasn't what I was trying to measure in the first place. I discovered this by chance, so forgive the lack of precision. I also don't have the source code anymore because I wasn't originally planning to report this discovery.
Results
| File Size | Consecutive Files | dump µs | dumps µs |
|---|---|---|---|
| 74 | 1 | 508 | 581 |
| 74 | 2 | 520 | 541 |
| 74 | 4 | 1153 | 1151 |
| 74 | 8 | 1930 | 1750 |
| 39184 | 1 | 6363 | 1086 |
| 39184 | 2 | 11261 | 1821 |
| 39184 | 4 | 38126 | 3521 |
| 39184 | 8 | 80411 | 6466 |
| 468218 | 1 | 82821 | 11921 |
| 468218 | 2 | 150234 | 38017 |
| 468218 | 4 | 302357 | 42137 |
| 468218 | 8 | 573450 | 78545 |
Conclusion
A cursory investigation into the cpython code suggests that the slow part is the sequential writing of the iterencode yield. The chunks are quite small.
CPython versions tested on:
3.10
Operating systems tested on:
macOS
Linked PRs
- gh-130076
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
首先检查链接的 PR gh-130076,以及 CPython 中与 iterencode 的顺序写入相关的 JSON 代码。复现报告中的 dump-versus-dumps 计时结果,然后验证该更改是否能在更大规模的情况下提升 dump 性能,同时不改变输出。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- backend
- Issue 类型
- 缺陷
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 35/100