Skip to content

Conversation

barneygale
Copy link
Contributor

@barneygale barneygale commented Jul 6, 2024

When os.walk() traverses into subdirectories in top-down mode, call os.path.join() once to add a trailing slash, and use string concatenation thereafter to generate child paths.

(this trick is already used in os.fwalk())

$ ./python -m timeit -s 'import os' 'list(os.walk("."))'
5 loops, best of 5: 41.4 msec per loop
5 loops, best of 5: 40.7 msec per loop
# --> 1.7% faster

When `os.walk()` traverses into subdirectories in top-down mode, call
`os.path.join()` once to add a trailing slash, and use string concatenation
thereafter to generate child paths.
@barneygale barneygale added the performance Performance or resource usage label Jul 6, 2024
@barneygale barneygale changed the title GH-119186: Slightly speed up os.walk(topdown=True) GH-119169: Slightly speed up os.walk(topdown=True) Jul 6, 2024
# above.
if followlinks or not islink(new_path):
stack.append(new_path)
if dirs:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How much of the gain is due to the elimination of os.join and how much due to the check on empty dirs? On my system a walk of a folder with github repositories (including the cpython repo) has dirs empty about 60% of the times.

@encukou encukou merged commit b19ad11 into python:main Sep 3, 2025
45 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
performance Performance or resource usage
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants