Python if vs try-except

前端 未结 7 1897
执笔经年
执笔经年 2020-12-05 23:16

I was wondering why the try-except is slower than the if in the program below.

def tryway():
    try:
        while True:
            alist.pop()
    except         


        
7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-06 00:15

    If you are really interested in speed, both of your contestants could do with losing some weight.

    while True: is slower than while 1: -- True is a global "variable" which is loaded and tested; 1 is a constant and the compiler does the test and emits an unconditional jump.

    while True: is redundant in ifway. Fold the while/if/break together: while alist != []:

    while alist != []: is a slow way of writing while alist:

    Try this:

    def tryway2():
        alist = range(1000)
        try:
            while 1:
                alist.pop()
        except IndexError:
            pass
    
    def ifway2():
        alist = range(1000)
        while alist:
            alist.pop()
    

    `

提交回复
热议问题