gh-103000: Optimise `dataclasses.asdict` for the common case by AlexWaygood · Pull Request #104364 · python/cpython
Now that PEP 709 has been implemented, this change speeds up the following benchmark by 15% on my machine (Windows, PGO-optimised non-debug build):
Benchmark:
from dataclasses import dataclass, asdict import timeit @dataclass class Foo: x: int @dataclass class Bar: x: Foo y: Foo z: Foo @dataclass class Baz: x: Bar y: Bar z: Bar foo = Foo(42) bar = Bar(foo, foo, foo) baz = Baz(bar, bar, bar) print(timeit.timeit(lambda: asdict(baz), number=250_000))
This idea was originally @DavidCEllis's, but prior to PEP 709, comprehensions had too much overhead to make it worthwhile. Now that PEP 709 has been implemented, the impact of the patch seems pretty different.
Co-authored-by: David Ellis ducksual@gmail.com