Last active
February 12, 2026 07:26
-
-
Save roganjoshp/ff4f30fd31542f12a6f0855f2cc94542 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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, | |
| ), | |
| ) | |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Peephole : 5.333e-06 sec
Search List : 6.028 sec
Search Existing List : 1.882 sec
Search Set : 6.472 sec