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

时间:2017-11-22 10:47:34

标签: python namedtuple

当我尝试将namedtuple转换为字典[python 2.7.12]时,使用以下方法,发现addr比第一种方法慢10倍以上。任何人都可以告诉我这背后的原因是什么?

namedtuple._as_dict()

1 个答案:

答案 0 :(得分:3)

因为._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