⚡️ Speed up method CompositeVocab.id2unit by 45%
#232
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.
📄 45% (0.45x) speedup for
CompositeVocab.id2unitinstanza/models/common/vocab.py⏱️ Runtime :
1.64 milliseconds→1.13 milliseconds(best of145runs)📝 Explanation and details
The optimized code achieves a 44% speedup through several micro-optimizations that reduce the overhead of Python's attribute and method lookups within tight loops:
Key optimizations:
Local variable caching for loop operations: The
items.appendmethod is cached as a local variable (append = items.append) before the loops. This eliminates repeated method lookups on theitemslist during each iteration, providing faster access since local variable lookup is faster than attribute lookup in Python.Cached instance variables:
self._id2unitandEMPTY_IDare cached as local variables (_id2unitandEMPTY) before the loops. This reduces the cost of attribute access during each iteration of the potentially large loops.Eliminated redundant conditional checks: The original code had a single loop with conditional logic inside (
if self.keyed). The optimized version splits this into two separate loops - one for keyed mode and one for non-keyed mode. This eliminates the repeated conditional check inside the loop, reducing overhead when processing many items.Minor string comparison optimization: Changed
if res == ""toif not res, which is marginally faster for empty string checks.Performance characteristics:
These optimizations are particularly effective for the large-scale test cases in the test suite, where the loops process hundreds or thousands of vocabulary items. The local variable caching becomes more beneficial as the loop iteration count increases, explaining why this optimization shows strong performance gains across the comprehensive test cases that include large vocabularies with 500-1000 keys.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
⏪ Replay Tests and Runtime
To edit these changes
git checkout codeflash/optimize-CompositeVocab.id2unit-mh4j6fbband push.