您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

当else做得最多时,最有效的方式来执行if-elif-elif-else语句?

当else做得最多时,最有效的方式来执行if-elif-elif-else语句?

编码…

options.get(something, doThisMostOfTheTime)()

…看起来应该是快,但它实际上是慢于ifelifelse结构,因为它要调用一个函数,它可以在一个紧密的循环一个显著的性能开销。

考虑这些例子…

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

…使用来自的用户时间time(1)

选项#4确实有额外的内存开销,需要为每个不同的键缺失添加一个新项目,因此,如果您期望数量众多的不同的键缺失,我会选择选项#3,它在原始构造。

其他 2022/1/1 18:29:27 有471人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶