2017-11-22 2 views
1

Wenn ich versucht, Nametuple in Dictionary [Python 2.7.12] zu konvertieren, mit den folgenden Methoden, namedtuple._as_dict() ist mehr als 10x mal langsamer als der erste Ansatz gefunden. Kann mir jemand sagen, was dahinter steckt?warum namedtuple._as_dict() ist langsamer als die Konvertierung mit dict()

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 

Antwort

2

Da ._asdict kehrt ein OrderedDictionary:

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

Hinweis, wenn Sie, um sich nicht, dann ein Wörterbuch-wörtliche Verwendung sollte der schnellste Weg sein:

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 
Verwandte Themen