Skip to content

Instantly share code, notes, and snippets.

@bigjason
Created June 25, 2011 15:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bigjason/1046586 to your computer and use it in GitHub Desktop.
Save bigjason/1046586 to your computer and use it in GitHub Desktop.
Benchmark of get methods with python
from __future__ import print_function
a_dict = {x: str(x) for x in range(1000)}
def with_get():
result1 = a_dict.get(-1, None)
result2 = a_dict.get(900, None)
def with_exception():
try:
result1 = a_dict[-1]
except KeyError:
result1 = None
try:
result2 = a_dict[900]
except KeyError:
result2 = None
def with_in():
result1 = a_dict[-1] if -1 in a_dict else None
result2 = a_dict[900] if 900 in a_dict else None
if __name__ == '__main__':
import timeit
import sys
using_get = timeit.Timer('with_get()', 'from __main__ import with_get')
using_exception = timeit.Timer('with_exception()', 'from __main__ import with_exception')
using_in = timeit.Timer('with_in()', 'from __main__ import with_in')
print(sys.version)
print()
print('with_get(): ', using_get.timeit())
print('with_exception():', using_exception.timeit())
print('with_in(): ', using_in.timeit())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment