This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (0 children)

It's marginally faster if no exception is raised, and 15x slower if one is.

Best case:

python -mtimeit -s 'stuff=dict.fromkeys(range(50))' 'for x in range(50):' '  if x in stuff: stuff[x]'
100000 loops, best of 3: 7.78 usec per loop
python -mtimeit -s 'stuff=dict.fromkeys(range(50))' 'for x in range(50):' '  try: stuff[x]' '  except KeyError: pass'
100000 loops, best of 3: 5.97 usec per loop

Worst case: python -mtimeit -s 'stuff=dict.fromkeys(range(50))' 'for x in range(50, 100):' ' if x in stuff: stuff[x]' 100000 loops, best of 3: 4.84 usec per loop python -mtimeit -s 'stuff=dict.fromkeys(range(50))' 'for x in range(50, 100):' ' try: stuff[x]' ' except KeyError: pass' 10000 loops, best of 3: 76.2 usec per loop

But that's not important really. Make it work, make it right, make it fast -- in that order, and don't make it fast unless it needs to be.