⚡️ Speed up function like_num by 1,072%
#12
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.
📄 1,072% (10.72x) speedup for
like_numinspacy/lang/yo/lex_attrs.py⏱️ Runtime :
10.2 milliseconds→872 microseconds(best of169runs)📝 Explanation and details
The optimized code achieves a 10.7x speedup by eliminating the most expensive operation in the original implementation. The key optimization is lazy initialization with caching of the stripped number words.
What was optimized:
Eliminated repeated expensive computation: The original code called
[strip_accents_text(num) for num in _num_words]on everylike_num()invocation, which was the performance bottleneck (95% of execution time per line profiler).Added lazy caching mechanism:
_get_num_words_stripped()computes the stripped words only once and stores them in a function attribute cache, converting the list to a set for O(1) lookups instead of O(n) list searches.Simplified lookup logic: Reduced from two separate membership checks (
text in _num_words_stripped or text.lower() in _num_words_stripped) to a single check after lowercasing once (stripped_text.lower() in _get_num_words_stripped()).Minor optimization: Changed
num_markersfrom list to tuple for faster membership testing.Why this is faster:
strip_accents_text()calls per function invocation (once per word in_num_words)strip_accents_text()call (on the input text only)Performance impact:
The tests show dramatic improvements especially for cases involving actual number word lookups (1000-4000% faster for many test cases). The optimization is most effective when the input text requires checking against the Yoruba number words, as evidenced by the large speedups in cases like
test_basic_digits()andtest_large_many_numwords().✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
lang/yo/test_text.py::test_yo_lex_attrs_capitals🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-like_num-mhmju9dhand push.