Try/Except vs. If in Dictionary Key Access Python Performance
ilhicas.com
ilhicas.com
Try the following:
a = [i for in range(10000)] if 9999 in a: print('yay I just looped over an entire array')
however:
a = {i:i for in range(10000)} if 9999 in a: print('yay I found a key in linear time')
Now, You might be an expert in Data Structures, but what makes you implicitly know how the 'IN' behaves in python, and that it won't convert to the keys() method of the dict to get a list with the same behaviour as in a list?
Because it would be the dumb way to do it. You have a lookup procedure to extract a value from a hash. A procedure to check if the key is present in the hash will look exactly the same, barring the value being returned.
Libraries usually work the same way as you would write yourself if you were trained in the task, so it's easy to guess.
I'll quote part of it, regarding your "so it's easy to guess"
"In the face of ambiguity, refuse the temptation to guess."
$ 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 $ 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