Python if vs try-except

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

    There is still faster way iterating with for, though sometimes we want list to physically shirink so we know how many are left. Then alist should be parameter to the generator. (John is also right for while alist:) I put the function to be a generator and used list(ifway()) etc. so the values are actualy used out of function (even not used):

    def tryway():
        alist = range(1000)
        try:
            while True:
                yield alist.pop()
        except IndexError:
            pass
    
    def whileway():
        alist = range(1000)
        while alist:
             yield alist.pop()
    
    def forway():
        alist = range(1000)
        for item in alist:
             yield item
    
    if __name__=='__main__':
        from timeit import Timer
        print "Testing Try"
        tr = Timer("list(tryway())","from __main__ import tryway")
        print tr.timeit(10000)
        print "Testing while"
        ir = Timer("list(whileway())","from __main__ import whileway")
        print ir.timeit(10000)
        print "Testing for"
        ir = Timer("list(forway())","from __main__ import forway")
        print ir.timeit(10000)
    
    J:\test>speedtest4.py
    Testing Try
    6.52174983133
    Testing while
    5.08004508953
    Testing for
    2.14167694497
    
    0 讨论(0)
提交回复
热议问题