⚡️ Speed up function merge_hooks
by 939%
#30
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.
📄 939% (9.39x) speedup for
merge_hooks
insrc/requests/sessions.py
⏱️ Runtime :
996 microseconds
→95.9 microseconds
(best of134
runs)📝 Explanation and details
Here is an optimized version of the provided Python program.
Explanation.
Reduction of Intermediate Data Structures:
- In the original
merge_setting
function, an intermediatemerged_setting
dictionary was created by converting the session settings to a list, then updated with the request settings, and then unnecessaryNone
values were removed. This process involved creating and discarding several temporary data structures.- In the optimized version, we avoid creating an intermediate dictionary and directly populate
merged_setting
with the non-None values from the session and request settings through a single iteration.Early Termination on Empty Hooks.
- The original
merge_hooks
checked for empty response hooks by comparing with[]
. The optimized version usesnot
directly which is slightly faster and more Pythonic.- This ensures we exit the function at the earliest possible point if the conditions for early termination are met.
✅ Correctness verification report:
🌀 Generated Regression Tests Details
📢 Feedback on this optimization?