python / python/cpython

Improve performance of dataclasses.asdict by caching field names

未关闭
#138,232 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

performance stdlib topic-dataclasses type-feature
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

Feature or enhancement

Proposal:

About 8 years ago @ericvsmith asked:

https://github.com/python/cpython/blob/c779f2324df06563b4ba3d70d0941e619ccaf5ff/Lib/dataclasses.py#L1381

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

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

首先检查 Lib/dataclasses.py 中 asdict 和 astuple 的实现部分,然后在开始任何工作之前检查关联的 PR gh-138233。运行提供的 pyperf 脚本以建立报告中的基线;完成后应保留 dataclass 的行为,同时实现所提议的字段名称缓存性能改进。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
performance
Issue 类型
功能
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
25/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。