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 | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
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.