python / python/cpython

Improve performance of dataclasses.asdict by caching field names

Open
#138,232 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

performance stdlib topic-dataclasses type-feature
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reviewing Lib/dataclasses.py around the asdict and astuple implementation, then inspect linked PR gh-138233 before doing any work. Run the supplied pyperf script to establish the reported baseline; completion should preserve dataclass behavior while achieving the proposed field-name caching performance improvement.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
performance
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.