编码…
options.get(something, doThisMostOfTheTime)()
…看起来应该是快,但它实际上是慢于if
… elif
…else
结构,因为它要调用一个函数,它可以在一个紧密的循环一个显著的性能开销。
考虑这些例子…
something = 'something'
for i in xrange(1000000):
if something == 'this':
the_thing = 1
elif something == 'that':
the_thing = 2
elif something == 'there':
the_thing = 3
else:
the_thing = 4
something = 'something'
options = {'this': 1, 'that': 2, 'there': 3}
for i in xrange(1000000):
the_thing = options.get(something, 4)
something = 'something'
options = {'this': 1, 'that': 2, 'there': 3}
for i in xrange(1000000):
if something in options:
the_thing = options[something]
else:
the_thing = 4
from collections import defaultdict
something = 'something'
options = defaultdict(lambda: 4, {'this': 1, 'that': 2, 'there': 3})
for i in xrange(1000000):
the_thing = options[something]
…并注意他们使用的cpu时间…
1.py: 160ms
2.py: 170ms
3.py: 110ms
4.py: 100ms
选项#4确实有额外的内存开销,需要为每个不同的键缺失添加一个新项目,因此,如果您期望数量众多的不同的键缺失,我会选择选项#3,它在原始构造。