Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-100562: improve performance of pathlib.Path.absolute() #100563

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

barneygale
Copy link
Contributor

@barneygale barneygale commented Dec 28, 2022

Increase performance of the absolute() method by calling os.getcwd() directly, rather than using the Path.cwd() class method. This avoids constructing an extra Path object (and the parsing/normalization that comes with it).

Decrease performance of the cwd() class method by calling the Path.absolute() method, rather than using os.getcwd() directly. This involves constructing an extra Path object. We do this to maintain a longstanding pattern where os functions are called from only one place, which allows them to be more readily replaced by users. As cwd() is generally called at most once within user programs, it's a good bargain.

# before
$ ./python -m timeit -s 'from pathlib import Path; p = Path("foo", "bar")' 'p.absolute()'
50000 loops, best of 5: 9.04 usec per loop
# after
$ ./python -m timeit -s 'from pathlib import Path; p = Path("foo", "bar")' 'p.absolute()'
50000 loops, best of 5: 5.02 usec per loop

Increase performance of the `absolute()` method by calling `os.getcwd()`
directly, rather than using the `Path.cwd()` class method. This avoids
constructing an extra `Path` object (and the parsing/normalization that
comes with it).

Decrease performance of the `cwd()` class method by calling the
`Path.absolute()` method, rather than using `os.getcwd()` directly. This
involves constructing an extra `Path` object. We do this to maintain a
longstanding pattern where `os` functions are called from only one place,
which allows them to be more readily replaced by users. As `cwd()` is
generally called at most once within user programs, it's a good bargain.
Lib/pathlib.py Show resolved Hide resolved
Lib/pathlib.py Show resolved Hide resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
3.12 awaiting review performance Performance or resource usage
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

5 participants