⚡️ Speed up function ambiguous_shift_open_unary_close by 207%
#215
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.
📄 207% (2.07x) speedup for
ambiguous_shift_open_unary_closeinstanza/models/constituency/in_order_oracle.py⏱️ Runtime :
27.5 microseconds→8.94 microseconds(best of63runs)📝 Explanation and details
The optimized code achieves a 207% speedup through two key optimizations:
1. Type checking optimization: Replaced
isinstance(obj, Class)withtype(obj) is not Class. Theisinstance()function involves method resolution order traversal and additional overhead, whiletype()with direct identity comparison (is) is much faster. This optimization is particularly effective here since the line profiler shows that type checking dominates execution time (81.7% and 65.7% of runtime respectively).2. List construction optimization: Eliminated expensive list slicing and concatenation operations (
gold_sequence[:gold_index] + [pred_transition, CloseConstituent()] + gold_sequence[gold_index:]) in favor of pre-allocating a result list and using slice assignment. This avoids creating multiple temporary lists and reduces memory allocations.The line profiler results confirm the impact: the original code spends most time on the
isinstancechecks (63,117 ns for the first check), while the optimized version reduces this to 16,710 ns. Since most test cases return early due to type check failures (18 out of 19 calls return None), the type checking optimization provides the primary performance benefit.These optimizations are most effective for workloads with frequent type checking where early returns are common, as evidenced by the test results showing that type mismatches dominate the execution patterns.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-ambiguous_shift_open_unary_close-mh35qf7nand push.