Skip to content

Instantly share code, notes, and snippets.

@RealBigB
Created October 2, 2015 07:22
Show Gist options
  • Save RealBigB/38f4579c543261f1400f to your computer and use it in GitHub Desktop.
Save RealBigB/38f4579c543261f1400f to your computer and use it in GitHub Desktop.
Timing the cost of a try/except block vs the cost of a key lookup...
from timeit import Timer
def eafp(d):
try:
return d["key"]
except KeyError:
return None
def lbyl(d):
if "key" in d:
return d["key"]
return None
dicts = [{"key":1}, {"nokey":1}]
t1 = Timer("[eafp(d) for d in dicts]", 'from __main__ import dicts, eafp')
t2 = Timer("[lbyl(d) for d in dicts]", 'from __main__ import dicts, lbyl')
print t1.timeit()
print t2.timeit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment