Skip to content

Instantly share code, notes, and snippets.

@mozeryansky
Created September 3, 2016 03:39
Show Gist options
  • Save mozeryansky/4a0872e9b2ff6e1704d07426ba829ea4 to your computer and use it in GitHub Desktop.
Save mozeryansky/4a0872e9b2ff6e1704d07426ba829ea4 to your computer and use it in GitHub Desktop.
Python 2.7 Array vs Set Performance
import timeit
print 'set/array of numbers'
print ''
print 'first in set:', timeit.timeit('1 in set([1, 2, 3, 4, 5, 6, 7, 8, 9])', number=10000000)
print 'last in set: ', timeit.timeit('9 in set([1, 2, 3, 4, 5, 6, 7, 8, 9])', number=10000000)
print 'not in set: ', timeit.timeit('0 in set([1, 2, 3, 4, 5, 6, 7, 8, 9])', number=10000000)
print ''
print 'first in array:', timeit.timeit('1 in [1, 2, 3, 4, 5, 6, 7, 8, 9]', number=10000000)
print 'last in array: ', timeit.timeit('9 in [1, 2, 3, 4, 5, 6, 7, 8, 9]', number=10000000)
print 'not in array: ', timeit.timeit('0 in [1, 2, 3, 4, 5, 6, 7, 8, 9]', number=10000000)
print ''
print 'set/array of strings'
print ''
print 'first in set:', timeit.timeit('"abc" in set(["abc", "def", "ghi", "jkl", "mno", "pqr", "stu", "vqx", "yz"])', number=10000000)
print 'last in set: ', timeit.timeit('"yz" in set(["abc", "def", "ghi", "jkl", "mno", "pqr", "stu", "vqx", "yz"])', number=10000000)
print 'not in set: ', timeit.timeit('"123" in set(["abc", "def", "ghi", "jkl", "mno", "pqr", "stu", "vqx", "yz"])', number=10000000)
print ''
print 'first in array:', timeit.timeit('"abc" in ["abc", "def", "ghi", "jkl", "mno", "pqr", "stu", "vqx", "yz"]', number=10000000)
print 'last in array: ', timeit.timeit('"yz" in ["abc", "def", "ghi", "jkl", "mno", "pqr", "stu", "vqx", "yz"]', number=10000000)
print 'not in array: ', timeit.timeit('"123" in ["abc", "def", "ghi", "jkl", "mno", "pqr", "stu", "vqx", "yz"]', number=10000000)
set/array of numbers
first in set: 6.70800304413
last in set: 6.68770003319
not in set: 6.62914586067
first in array: 0.256216049194
last in array: 1.4436621666
not in array: 1.56732106209
set/array of strings
first in set: 6.3961379528
last in set: 6.45437002182
not in set: 6.5248670578
first in array: 0.362590074539
last in array: 1.15092992783
not in array: 1.27027010918
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment