Skip to content

Instantly share code, notes, and snippets.

@thomas-scrace
Last active December 30, 2015 09:19
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 thomas-scrace/7808863 to your computer and use it in GitHub Desktop.
Save thomas-scrace/7808863 to your computer and use it in GitHub Desktop.
Testing 'x in s' performance for various python sequence types
import timeit
seq_types = ('set', 'list', 'tuple')
intervals = (10, 100, 1000)
def test(t, i):
r = t(range(i))
for j in range(i):
if i in r:
pass
for t in seq_types:
for i in intervals:
duration = timeit.timeit(
'test({t}, {i})'.format(t=t, i=i),
setup='from __main__ import test', number=10000
)
print '{i}-long {t} took {d}'.format(
i=i, t=t, d=duration
)
@thomas-scrace
Copy link
Author

My results:

10-long set took 0.0126779079437
100-long set took 0.0721209049225
1000-long set took 0.667522907257
10-long list took 0.0193102359772
100-long list took 1.023209095
1000-long list took 98.0308930874
10-long tuple took 0.0185379981995
100-long tuple took 1.02909088135
1000-long tuple took 97.4343318939

Sets win by a mile. Tuples are fractionally faster at this than lists.

The time required for each type rises super-linearly with the length of the sequence.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment