Python if vs try-except

前端 未结 7 1910
执笔经年
执笔经年 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:14

    You're setting alist only once. The first call to "tryway" clears it, then every successive call does nothing.

    def tryway():
        alist = range(1000)
        try:
            while True:
                alist.pop()
        except IndexError:
            pass
    
    def ifway():
        alist = range(1000)
        while True:
            if alist == []:
                break
            else:
                alist.pop()
    if __name__=='__main__':
        from timeit import Timer
        print "Testing Try"
        tr = Timer("tryway()","from __main__ import tryway")
        print tr.timeit(10000)
        print "Testing If"
        ir = Timer("ifway()","from __main__ import ifway")
        print ir.timeit(10000)
    
    >>> Testing Try
    >>> 2.09539294243
    >>> Testing If
    >>> 2.84440898895
    

提交回复
热议问题