为什么`dataclasses.asdict(obj)`比`obj.__dict__()`慢10倍以上?

9 浏览
0 Comments

为什么`dataclasses.asdict(obj)`比`obj.__dict__()`慢10倍以上?

我正在使用Python 3.6和来自ericvsmithdataclasses回退包。

调用dataclasses.asdict(my_dataclass)似乎比调用my_dataclass.__dict__慢约10倍:

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

0