Skip to content

Instantly share code, notes, and snippets.

@rnag
Last active August 25, 2022 20:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rnag/9abc4c8b991bb6f918fbee3e45c487fb to your computer and use it in GitHub Desktop.
Save rnag/9abc4c8b991bb6f918fbee3e45c487fb to your computer and use it in GitHub Desktop.
dataclass re-decoration timing
# 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
@rnag
Copy link
Author

rnag commented Aug 25, 2022

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 the dataclass 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 for dataclass(A) ~= dataclass(B), which means that we should avoid repeat calls to the dataclass() function if at all possible.

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