Improve performance of dataclasses.asdict by caching field names
未關閉
還沒有人認領這個 Issue。
performance
stdlib
topic-dataclasses
type-feature
- 主要語言
- Python
- 星號
- 77.2k
- 分支
- 35.9k
- PR 合併指標
- PR 指標待擷取
描述
Feature or enhancement
Proposal:
About 8 years ago @ericvsmith asked:
By caching the field names of a dataclass on the class the performance improves:
asdict: Mean +- std dev: [main] 2.33 us +- 0.14 us -> [pr] 1.65 us +- 0.08 us: 1.41x faster
astuple: Mean +- std dev: [main] 2.77 us +- 0.15 us -> [pr] 2.15 us +- 0.09 us: 1.29x faster
f.__getstate__(): Mean +- std dev: [main] 941 ns +- 64 ns -> [pr] 360 ns +- 18 ns: 2.61x faster
Benchmark hidden because not significant (1): instance creation
Geometric mean: 1.47x faster
Test script
(executed on non-pgo build)
import pyperf
setup = """
from dataclasses import dataclass, asdict, astuple
from pickle import dumps
@dataclass
class Simple:
i : int
s : str
l : list
s = Simple(10, 'hi', [3, 1, 4, 1])
@dataclass(frozen=True, slots=True)
class Frozen:
i : int
s : str
l : list
f = Frozen(10, 'hi', [3, 1, 4, 1])
f.__getstate__()
"""
runner = pyperf.Runner()
runner.timeit(name="instance creation", stmt="Simple(10, 'hi', [3, 1, 4, 1])", setup=setup)
runner.timeit(name="asdict", stmt="asdict(s)", setup=setup)
runner.timeit(name="astuple", stmt="astuple(s)", setup=setup)
runner.timeit(name="f.__getstate__()", stmt="f.__getstate__()", setup=setup)
The main downside of caching the field names is that (per dataclass, not per instance) we have an additional private field on the class with a list of strings.
Has this already been discussed elsewhere?
No response given
Links to previous discussion of this feature:
No response
Linked PRs
- gh-138233
貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
研究方向
先檢閱 Lib/dataclasses.py 中 asdict 和 astuple 的實作部分,然後在進行任何工作之前檢查連結的 PR gh-138233。執行提供的 pyperf 指令碼,以建立報告中的基準;完成後應保留 dataclass 的行為,同時實現所提議的欄位名稱快取效能改進。
由索引模型根據 Issue 內容生成。
評估
- 技術堆疊
- python
- 領域
- performance
- Issue 類型
- 功能
- 難度
- 4/5
- 預估耗時
- 3-5 天
- 活躍度
- 停滯
- 描述清晰度
- 基本清楚
- 新手友好度
- 25/100