Skip to content

Instantly share code, notes, and snippets.

@queertypes
Created May 2, 2013 16:54
Show Gist options
  • Save queertypes/5503619 to your computer and use it in GitHub Desktop.
Save queertypes/5503619 to your computer and use it in GitHub Desktop.
A toy microbenchmark of the performance of 'in' in Python on various data structures.
from timeit import timeit as t
# 1 << 24 = 16 million elements
# Python 2.7
>>> t('needle in x', 'x, needle = range(1<<24), 1<<10')
13.510631084442139
>>> t('x.index(needle)', 'x, needle = range(1<<24), 1<<10')
14.749315023422241
>>> t('needle in x', 'x, needle = set(range(1<<24)), 1<<10')
0.06663703918457031
>>> t('needle in x', 'x, needle = dict(zip(range(1<<24), range(1<<24))), 1<<10')
0.06418609619140625
>>> t('x[needle]', 'x, needle = dict(zip(range(1<<24), range(1<<24))), 1<<10')
0.06438708305358887
# Python 3.3
>>> t('needle in x', 'x, needle = range(1<<24), 1<<10')
0.21385418299905723
>>> t('x.index(needle)', 'x, needle = range(1<<24), 1<<10')
0.3530631560024631
>>> t('needle in x', 'x, needle = set(range(1<<24)), 1<<10')
0.07136751699727029
>>> t('needle in x', 'x, needle = dict(zip(range(1<<24), range(1<<24))), 1<<10')
0.07094786499874317
>>> t('x[needle]', 'x, needle = dict(zip(range(1<<24), range(1<<24))), 1<<10')
0.06622415599849774
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment