Created
October 2, 2015 07:22
-
-
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...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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