gpt4 book ai didi

python - 为什么 namedtuple._as_dict() 比使用 dict() 转换慢

转载 作者:太空宇宙 更新时间:2023-11-04 00:26:00 25 4
gpt4 key购买 nike

当我尝试使用以下方法将 namedtuple 转换为字典 [python 2.7.12] 时,发现 namedtuple._as_dict() 比第一种方法慢 10 倍以上。谁能告诉我这背后的原因是什么?

In [1]: Container = namedtuple('Container', ['name', 'date', 'foo', 'bar'])

In [2]: c = Container('john','10-2-2017',20.78,'python')

In [3]: %timeit dict(name=c.name,date=c.date,foo=c.foo,bar=c.bar)
The slowest run took 7.57 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 536 ns per loop

In [4]: %timeit c._asdict()
The slowest run took 4.84 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 7.19 µs per loop

最佳答案

因为 ._asdict 返回一个 OrderedDictionary:

>>> c._asdict()
OrderedDict([('name', 'john'), ('date', '10-2-2017'), ('foo', 20.78), ('bar', 'python')])
>>>

请注意,如果您不关心顺序,那么使用字典文字应该是最快的方法:

In [5]: %timeit dict(name=c.name,date=c.date,foo=c.foo,bar=c.bar)
...:
The slowest run took 6.13 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 795 ns per loop

In [6]: %timeit c._asdict()
The slowest run took 4.13 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 2.25 µs per loop

In [7]: %timeit {'name':c.name, 'date':c.date, 'foo':c.foo, 'bar':c.bar}
The slowest run took 7.08 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 424 ns per loop

关于python - 为什么 namedtuple._as_dict() 比使用 dict() 转换慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47432731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com