Skip to content

Instantly share code, notes, and snippets.

@roganjoshp
Last active February 12, 2026 07:26
Show Gist options
  • Select an option

  • Save roganjoshp/ff4f30fd31542f12a6f0855f2cc94542 to your computer and use it in GitHub Desktop.

Select an option

Save roganjoshp/ff4f30fd31542f12a6f0855f2cc94542 to your computer and use it in GitHub Desktop.
import timeit
HAYSTACK = range(10_000_000)
NEEDLE = 9_999_999
# Assuming we already had a list in the first place, so the overhead only
# applies if we want to convert that to a set() for a single lookup
HAYSTACK_LIST_PREFORMED = list(HAYSTACK)
def peephole():
return NEEDLE in HAYSTACK
def search_list():
haystack = list(HAYSTACK)
return NEEDLE in haystack
def search_existing_list():
return NEEDLE in HAYSTACK_LIST_PREFORMED
def search_set():
haystack = set(HAYSTACK)
return NEEDLE in haystack
if __name__ == "__main__":
print(
"Peephole",
timeit.timeit(
"peephole()",
setup="from __main__ import peephole, NEEDLE, HAYSTACK",
number=20,
),
)
print(
"Search List",
timeit.timeit(
"search_list()",
setup="from __main__ import search_list, NEEDLE, HAYSTACK",
number=20,
),
)
print(
"Search Existing List",
timeit.timeit(
"search_existing_list()",
setup="from __main__ import search_existing_list, NEEDLE, HAYSTACK_LIST_PREFORMED",
number=20,
),
)
print(
"Search Set",
timeit.timeit(
"search_set()",
setup="from __main__ import search_set, NEEDLE, HAYSTACK",
number=20,
),
)
@roganjoshp
Copy link
Author

roganjoshp commented Feb 12, 2026

Peephole : 5.333e-06 sec
Search List : 6.028 sec
Search Existing List : 1.882 sec
Search Set : 6.472 sec

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