Last active
August 25, 2022 20:58
-
-
Save rnag/9abc4c8b991bb6f918fbee3e45c487fb to your computer and use it in GitHub Desktop.
dataclass re-decoration timing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# See comment below for an explanation of what this script is testing! | |
from dataclasses import dataclass, is_dataclass | |
from timeit import timeit | |
@dataclass | |
class A: | |
a: int = 10 | |
class B: | |
a: int = 10 | |
assert is_dataclass(A) | |
assert not is_dataclass(B) | |
n = 1_000 | |
print(timeit('dataclass(A)', globals=globals(), number=n)) # 0.138 | |
print(timeit('dataclass(B)', globals=globals(), number=n)) # 0.134 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Notes
Ideally, the performance timing of a call to
dataclass(A)
should be in O(1) time, and be as close to zero as possible - which indicates that thedataclass
function is a no-op in scenarios where a class is already a dataclass.However, what we instead observe, is that it takes the same time to call the
@dataclass
decorator (or function), regardless if the input class is already a dataclass or not. Thus, timings fordataclass(A) ~= dataclass(B)
, which means that we should avoid repeat calls to thedataclass()
function if at all possible.