⚡️ Speed up function ttfFontProperty by 17%
#219
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.
📄 17% (0.17x) speedup for
ttfFontPropertyinlib/matplotlib/font_manager.py⏱️ Runtime :
850 microseconds→724 microseconds(best of41runs)📝 Explanation and details
The optimized code achieves a 17% speedup through two key optimizations that reduce redundant work in regex pattern matching and string operations:
1. Pre-compiled Regular Expressions
The original code used string patterns in
_weight_regexesthat were compiled on-demand duringre.fullmatch()andre.search()calls inside theget_weight()function. The optimization pre-compiles all regex patterns at module load time, storing compiled regex objects instead of strings. This eliminates repeated regex compilation overhead, which is particularly beneficial sinceget_weight()is called for every font and may iterate through multiple patterns.2. Optimized String Operations
str.find() >= 0with the more efficientinoperator for substring searches when checking style keywords like 'oblique', 'italic', and 'regular'stylesvariable), reducing memory allocation overheadany()calls for stretch keyword checking, providing minor performance gainsPerformance Impact Analysis
Based on the function references,
ttfFontPropertyis called in critical rendering paths within matplotlib's backends (Cairo and SVG), where it processes font information for text rendering. The SVG backend particularly shows intensive usage within mathtext parsing loops, making this optimization especially valuable for:The test results show the optimization is most effective for edge cases involving fallback weight detection (68-83% faster) where multiple regex patterns are tested, while maintaining consistent 5-6% improvements for typical font processing scenarios. This suggests the regex compilation overhead was a significant bottleneck in the original implementation.
✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-ttfFontProperty-miy5u6nqand push.