Skip to content

Conversation

@barneygale
Copy link
Contributor

@barneygalebarneygale 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.
@barneygalebarneygale added the performance Performance or resource usage label Jul 6, 2024
@barneygalebarneygale 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.
iffollowlinksornotislink(new_path):
stack.append(new_path)
ifdirs:
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.

@encukouencukou merged commit b19ad11 into python:mainSep 3, 2025
45 checks passed
lkollar pushed a commit to lkollar/cpython that referenced this pull request Sep 9, 2025
…121431) pythonGH-119186: Slightly speed up `os.walk(topdown=True)` 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.
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

performancePerformance or resource usage

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants

@barneygale@eendebakpt@encukou