Skip to content

Instantly share code, notes, and snippets.

@internetimagery
Created July 23, 2026 09:02
Show Gist options
  • Select an option

  • Save internetimagery/f9f7482eb90b0a84fc7a75dee1e4fe3d to your computer and use it in GitHub Desktop.

Select an option

Save internetimagery/f9f7482eb90b0a84fc7a75dee1e4fe3d to your computer and use it in GitHub Desktop.
More efficient BFS
# 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