Created
July 23, 2026 09:02
-
-
Save internetimagery/f9f7482eb90b0a84fc7a75dee1e4fe3d to your computer and use it in GitHub Desktop.
More efficient BFS
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
| # OLD | |
| from collections import deque | |
| queue = deque(starting_values) | |
| while queue: | |
| item = queue.popleft() | |
| queue.extend(item.children) | |
| # ... do things with item ... | |
| # Less alloc | |
| from itertools import chain | |
| queue = [starting_values] | |
| for item in chain.from_iterable(queue): | |
| queue.append(item.children) | |
| # ... do things with item ... | |
| # Only allocating a pointer to our iterator location, and only adding to the list one item for each set of children. 30x faster |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment