2017-11-22 15 views
1

namedtupleを辞書[python 2.7.12]に変換しようとしたときに、以下の方法を使用した場合、namedtuple._as_dict()が最初のアプローチよりも10倍以上遅くなりました。誰かがこれの背後にある理由を教えてもらえますか?namedtuple._as_dict()が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 

答えて

2

OrderedDictionary戻り._asdictため:

>>> 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 
関連する問題