本文共 986 字,大约阅读时间需要 3 分钟。
代码…
options.get(something, doThisMostOfTheTime)()
…看起来它应该更快,但它实际上比if … elif … else构造,因为它必须调用一个函数,这可能是一个严重的性能开销在一个紧的循环。
考虑这些例子…
1.py
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
2.py
something = 'something'
options = {'this': 1, 'that': 2, 'there': 3}
for i in xrange(1000000):
the_thing = options.get(something, 4)
3.py
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
4.py
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
…使用用户时间从time(1)。
选项#4确实有额外的内存开销,为每个不同的密钥未命中添加一个新的项目,所以如果你期望无限多个不同的密钥未命中,我会选择#3,这仍然是一个重大的改进原始结构。
转载地址:http://dcips.baihongyu.com/