python中if elif语句优化_python – 最有效的方式做一个if-elif-elif-else语句当else做的最多?...

代码…

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,这仍然是一个重大的改进原始结构。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值