Skip to content

Instantly share code, notes, and snippets.

@Ricks-Lab
Last active May 19, 2022 12:10
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 Ricks-Lab/82ee51d7d0457f0f8457f3598fa8c57b to your computer and use it in GitHub Desktop.
Save Ricks-Lab/82ee51d7d0457f0f8457f3598fa8c57b to your computer and use it in GitHub Desktop.
String Search in a list/tuple/set of Strings
#!/usr/bin/python3
import timeit
import gc
gc.disable()
test_list = ['rick', 'junk', 'fred', 'exclamation point', 'fried', 'rickster', 'john', 'johnathan', 'nathan', 'a', 'b', 'r']
test_set = {'rick', 'junk', 'fred', 'exclamation point', 'fried', 'rickster', 'john', 'johnathan', 'nathan', 'a', 'b', 'r'}
test_tup = ('rick', 'junk', 'fred', 'exclamation point', 'fried', 'rickster', 'john', 'johnathan', 'nathan', 'a', 'b', 'r')
def search_in_set():
for test_word in ['rick', 'flib', 'fried', 'x', 'r']:
if test_word in test_set: pass
def search_in_list():
for test_word in ['rick', 'flib', 'fried', 'x', 'r']:
if test_word in test_list: pass
def search_in_tup():
for test_word in ['rick', 'flib', 'fried', 'x', 'r']:
if test_word in test_tup: pass
print('Search in List time: {}'.format(timeit.timeit(search_in_list)))
print('Search in Tuple time: {}'.format(timeit.timeit(search_in_tup)))
print('Search in Set time: {}'.format(timeit.timeit(search_in_set)))
@Ricks-Lab
Copy link
Author

Ricks-Lab commented May 19, 2022

With garbage collection:

  • Search in List time: 0.4352628909982741
  • Search in Tuple time: 0.45622857683338225
  • Search in Set time: 0.21148645295761526

Without garbage collection:

  • Search in List time: 0.4409587411209941
  • Search in Tuple time: 0.4597308330703527
  • Search in Set time: 0.19358495506457984

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