Skip to content

Instantly share code, notes, and snippets.

@capttwinky
Created July 11, 2013 01:07
Show Gist options
  • Save capttwinky/5971681 to your computer and use it in GitHub Desktop.
Save capttwinky/5971681 to your computer and use it in GitHub Desktop.
try / except is slllloooooowwwww for key checking. use the built in membership test instead.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
import timeit
import string
import pprint
def exfn(d_in, key):
try:
d_in[key]
except KeyError:
return False
return True
def iffn(d_in, key):
if key in d_in:
return True
return False
dict_arg = {s:ord(s) for s in string.printable}
times = {
'ex_raised': timeit.timeit('exfn({0}, "poop")'.format(dict_arg),
setup="from __main__ import exfn"),
'ex_found': timeit.timeit('exfn({0}, "D")'.format(dict_arg),
setup="from __main__ import exfn"),
'if_notfound': timeit.timeit('iffn({0}, "poop")'.format(dict_arg),
setup="from __main__ import iffn"),
'if_found': timeit.timeit('iffn({0}, "E")'.format(dict_arg),
setup="from __main__ import iffn")
}
pprint.pprint(times)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment