why namedtuple._as_dict() is slower than conversion using dict()

Viewed 2910

When i tried to convert namedtuple to dictionary[python 2.7.12], using following methods, namedtuple._as_dict() is found more than 10x times slower than first approach. Can anybody tell me what may reason behind this be?

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
1 Answers

Because ._asdict returns an OrderedDictionary:

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

Note, if you don't care about order, then using a dictionary-literal should be the fastest way:

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
Related