我正在使用 Python 3.6 和来自ericvsmithdataclasses
的backport 包。
似乎 calldataclasses.asdict(my_dataclass)
比 call 慢 10 倍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
这是预期的行为吗?在什么情况下我应该使用dataclasses.asdict(obj)
而不是obj.__dict__
?
编辑:使用__dict__.copy()
并没有太大的区别:
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