⚡️ Speed up function known_nicknames by 113%
#226
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.
📄 113% (1.13x) speedup for
known_nicknamesinstanza/resources/default_packages.py⏱️ Runtime :
318 microseconds→149 microseconds(best of578runs)📝 Explanation and details
The optimized code achieves a 113% speedup through two key improvements:
1. Efficient Dictionary Value Extraction
list(value for key, value in TRANSFORMER_NICKNAMES.items())creates a generator expression that iterates over key-value pairs, discarding keyslist(TRANSFORMER_NICKNAMES.values())directly extracts dictionary values without creating unnecessary key-value tuples2. In-Place Sorting vs. Creating New Sorted List
sorted(nicknames, key=lambda x: -len(x))creates a new list and uses a lambda function to negate lengthsnicknames.sort(key=len, reverse=True)sorts the existing list in-place using the built-inlenfunction withreverse=TrueThe line profiler confirms these improvements: the dictionary extraction time drops from 651,272ns to 69,467ns (89% faster), and the sorting time decreases from 700,842ns to 170,034ns (76% faster).
These optimizations are particularly effective for the typical use case with ~70 transformer nicknames in the dictionary, and scale well for larger datasets as shown in the test cases with 1000+ nicknames. The optimizations maintain identical functionality while being more memory-efficient and CPU-friendly.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-known_nicknames-mh4hd6mhand push.