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

标签 python namedtuple

当我尝试使用以下方法将 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/

相关文章:

Python 脚本和标准输出

python: importlib.import_module ("time") 但时间没有全局定义

arrays - 如何在 Julia 1.6.0 中使用 NamedTuples 初始化数组?

python - 将命名元组高效插入 pandas 数据框中

python - SQLAlchemy 中的总计分组

python - 尝试使用正则表达式在 python 中删除字符 EM DASH "—"(—)

python - namedtuple 字段在初始化期间的类型转换

python - NamedTuple 声明并在一行中使用

javascript - 如何将CasperJS调试结果打印到文本文件

python - Python 命名元组的可变默认参数