Skip to content

gh-103000: Optimise dataclasses.asdict for the common case#104364

Merged
AlexWaygood merged 3 commits intopython:mainfrom
AlexWaygood:dataclasses-perf
May 10, 2023
Merged

gh-103000: Optimise dataclasses.asdict for the common case#104364
AlexWaygood merged 3 commits intopython:mainfrom
AlexWaygood:dataclasses-perf

Conversation

@AlexWaygood
Copy link
Member

@AlexWaygood AlexWaygood commented May 10, 2023

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 [email protected]

Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

performance Performance or resource usage

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants