⚡️ Speed up method CancelScope.__enter__ by 15%
#3
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.
📄 15% (0.15x) speedup for
CancelScope.__enter__insrc/anyio/_backends/_asyncio.py⏱️ Runtime :
1.69 milliseconds→1.46 milliseconds(best of74runs)📝 Explanation and details
The optimized code achieves a 15% speedup through several key optimizations:
1. WeakKeyDictionary Access Pattern (12.9% vs 10.5% time)
try/except KeyErrorwith_task_states.get(host_task)in__enter__.get()is faster than exception handling for the common case where tasks already exist2. Reduced Attribute Lookups in Hot Loops
_deliver_cancellation, cachedself._tasks,self._host_task, andorigin._cancel_reasonas local variables3. Fast-path for math.inf Deadline Check
__enter__instead of always calling_timeout()_timeout()formath.infcase4. Optimized Attribute Access with getattr()
task._must_cancelandtask._fut_waiterwithgetattr()calls to avoid type ignore comments5. Branch Prediction Improvements
should_retry = Trueonly when cancellation is actually attemptedThe optimizations are most effective for high-frequency context manager usage and nested scope hierarchies, as shown by the line profiler results where
__enter__time reduced from 11.6ms to 8.6ms total. The WeakKeyDictionary optimization alone accounts for most of the performance gain in typical async workloads.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-CancelScope.__enter__-mhfo6i1uand push.