Hacker News new | ask | show | jobs
by carapace 2979 days ago
Use try..except.. when you expect it to mostly succeed.

    $ python -m timeit -s "a={k:k  for k in range(10000)}" 'try:
       b=a[10001]
    except:
       pass'
    1000000 loops, best of 3: 0.276 usec per loop

    $ python -m timeit -s "a={k:k  for k in range(10000)}" 'try:
       b=a[1]    
    except:
       pass'
    10000000 loops, best of 3: 0.0255 usec per loop

"try" is fast, "except" is slow
2 comments

Thanks for the input, yes I've since read that the problem lies on the exception catch, and definitely the time toll is in it.
However...

    $ python -m timeit -s "a={k:k  for k in range(10000)}" 'if 10001 in a:
       b=a[10001]
    else:
       pass'
    100000000 loops, best of 3: 0.0187 usec per loop
I gotta say, I didn't expect that. I thought the try..except.. for keys in the dict would be faster than this form. TIL