⚡️ Speed up method CaptureQueriesContext.__exit__ by 1,431%
#115
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.
📄 1,431% (14.31x) speedup for
CaptureQueriesContext.__exit__indjango/test/utils.py⏱️ Runtime :
15.0 microseconds→977 nanoseconds(best of181runs)📝 Explanation and details
The optimization achieves a 1430% speedup through two key algorithmic improvements:
1. Signal.connect() - O(n) to O(1) duplicate detection:
any(r_key == lookup_key for r_key, _, _, _ in self.receivers)- a linear search through all receivers (O(n))self._lookup_keysset for O(1) lookup key existence checks, reducing duplicate detection from O(n) to O(1)2. CaptureQueriesContext.exit() - Redundant signal reconnection elimination:
request_started.connect(reset_queries)when disconnected, even if already connected (629,744ns per call)_reset_queries_connectedflag to avoid redundant reconnections3. Minor cache optimization:
sender_receivers_cachewhenuse_caching=True, avoiding unnecessary dictionary operationsTest case performance benefits:
__exit__calls show 1248-1683% improvements due to eliminated redundant signal operations✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-CaptureQueriesContext.__exit__-mh6kt6y6and push.