GH-119169: Slightly speed up os.walk(topdown=True) (GH-121431)

GH-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.
This commit is contained in:
Barney Gale 2025-09-03 12:57:01 +01:00 committed by GitHub
parent 984d928a22
commit b19ad11027
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 12 additions and 8 deletions

View file

@ -417,14 +417,16 @@ def walk(top, topdown=True, onerror=None, followlinks=False):
# Yield before sub-directory traversal if going top down
yield top, dirs, nondirs
# Traverse into sub-directories
for dirname in reversed(dirs):
new_path = join(top, dirname)
# bpo-23605: os.path.islink() is used instead of caching
# entry.is_symlink() result during the loop on os.scandir() because
# the caller can replace the directory entry during the "yield"
# above.
if followlinks or not islink(new_path):
stack.append(new_path)
if dirs:
prefix = join(top, top[:0]) # Add trailing slash
for dirname in reversed(dirs):
new_path = prefix + dirname
# bpo-23605: os.path.islink() is used instead of caching
# entry.is_symlink() result during the loop on os.scandir() because
# the caller can replace the directory entry during the "yield"
# above.
if followlinks or not islink(new_path):
stack.append(new_path)
else:
# Yield after sub-directory traversal if going bottom up
stack.append((top, dirs, nondirs))