⚡️ Speed up function like_num by 47%
#10
Open
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.
📄 47% (0.47x) speedup for
like_numinspacy/lang/tn/lex_attrs.py⏱️ Runtime :
5.95 milliseconds→4.06 milliseconds(best of130runs)📝 Explanation and details
The optimized code achieves a 46% speedup through several key performance optimizations:
1. Set-based membership lookups with lazy caching: The most impactful change converts list membership checks (
_num_wordsand_ordinal_words) to set lookups. Sets provide O(1) average-case lookup time versus O(n) for lists. The optimization uses lazy initialization with caching on the function object to avoid overhead on first call while maintaining the same external behavior.2. Conditional string processing: Instead of always calling
text.replace(",", "").replace(".", ""), the optimized version first checks if commas or periods exist using',' in text or '.' in text. This eliminates unnecessary string operations for the majority of inputs that don't contain these characters.3. Improved leading character checks: Replaces
text.startswith(("+", "-", "±", "~"))withtext and text[0] in "+-±~", which is faster for single character checks and includes a safety check for empty strings.4. Optimized fraction validation: Adds a preliminary
"/" in textcheck before the more expensivetext.count("/") == 1operation, providing early exit for non-fractional inputs.5. Enhanced ordinal suffix checking: Adds a length check (
len(text_lower) > 2) before string slicing operations, avoiding unnecessary work on short strings.Performance impact by test case type:
The optimizations are particularly effective for workloads with many word-based number lookups and mixed input types, while maintaining identical functionality and correctness.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-like_num-mhmjhccyand push.