Python if vs try-except

前端 未结 7 1878
执笔经年
执笔经年 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-05 23:59

    Just thought to toss this into the mix: I tried the following script below which seems to suggest that handling an exception is slower than handling an else statement:

    import time
    
    n = 10000000
    l = range(0, n)
    t0 = time.time()
    for i in l:
        try:
            i[0]
        except:
            pass
    t1 = time.time()
    for i in l:
        if type(i) == list():
            print(i)
        else:
            pass
    t2 = time.time()
    print(t1-t0)
    print(t2-t1)
    

    gives:

    5.5908801555633545
    3.512694835662842
    

    So, (even though I know someone will likely comment upon the use of time rather than timeit), there appears to be a ~60% slow down using try/except in loops. So, perhaps better to go with if/else when going through a for loop of several billion items.

提交回复
热议问题