I am using Python 3.6 and the dataclasses
backport package from ericvsmith.
It seems that calling dataclasses.asdict(my_dataclass)
is ~10x slower than calling my_dataclass.__dict__
:
In [172]: @dataclass
...: class MyDataClass:
...: a: int
...: b: int
...: c: str
...:
In [173]: %%time
...: _ = [MyDataClass(1, 2, "A" * 1000).__dict__ for _ in range(1_000_000)]
...:
CPU times: user 631 ms, sys: 249 ms, total: 880 ms
Wall time: 880 ms
In [175]: %%time
...: _ = [dataclasses.asdict(MyDataClass(1, 2, "A" * 1000)) for _ in range(1_000_000)]
...:
CPU times: user 11.3 s, sys: 328 ms, total: 11.6 s
Wall time: 11.7 s
Is this expected behavior? In what cases should I have to use dataclasses.asdict(obj)
instead of obj.__dict__
?
Edit: Using __dict__.copy()
does not make a big difference:
In [176]: %%time
...: _ = [MyDataClass(1, 2, "A" * 1000).__dict__.copy() for _ in range(1_000_000)]
...:
CPU times: user 922 ms, sys: 48 ms, total: 970 ms
Wall time: 970 ms
asdict
will create and return new dict object, and recursive and convert any other data-class instances into dicts, whereas__dict__
simply returns a reference to the namespace of the object, something you probably don't want to mutate, for example...