Speed up exception handling#1038
Open
akx wants to merge 2 commits into
Open
Conversation
`contextlib.contextmanager`s are much slower than `try:except:`, and here they occur in very hot paths.
`try: except:` blocks are free on modern Pythons when exceptions aren't raised. Entering a `@contextmanager`'d block is much less free, and there are hot paths (e.g. reading from a sync socket) where it's worth avoiding that overhead. For consistency, this retires the use of `map_exceptions` everywhere. New exception blocks are marked nocover, since they weren't actually tested before either.
Merging this PR will not alter performance
Comparing Footnotes
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
@contextmanageris slow, and it's used in hot paths for every request both in httpcore2 and httpx2.This PR replaces uses of
map_exceptionsandmap_httpcore_exceptionswith faster alternatives.On my machine, a pytest-benchmark test shows a nearly 10% speed increase on a microbenchmark that retrieves a file from a local Caddy (see source in the details block below)
test_bench1.py
and a hyperfine check for the same says ~5%, but that's with all of the overhead:
Rebase of
map_httpcore_exceptionsto not be a context manager encode/httpx#3778Checklist