⚡️ Speed up function split_dict_by_key_prefix by 10%
#87
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.
📄 10% (0.10x) speedup for
split_dict_by_key_prefixinplotly/shapeannotation.py⏱️ Runtime :
780 microseconds→712 microseconds(best of207runs)📝 Explanation and details
The optimization delivers a 9% speedup through two key changes:
1. Efficient dictionary iteration: Changed from
for k in d.keys(): ... d[k]tofor k, v in d.items(). The original approach performs two dictionary lookups per iteration - one to get the key fromd.keys()and another to retrieved[k]. The optimized version gets both key and value in a single operation, eliminating redundant hash table lookups.2. Faster dictionary initialization: Replaced
dict()constructor calls with literal{}syntax. Dictionary literals are parsed and optimized at compile time, avoiding the overhead of function calls to thedict()constructor.Performance impact by test case:
The line profiler shows the optimization reduces time spent on dictionary value retrieval (lines with
d[k]assignments) from 34.5% to 31.7% of total runtime, while the iteration overhead slightly increases due to unpacking but overall delivers net performance gains.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-split_dict_by_key_prefix-mhgeffhuand push.