⚡️ Speed up method Char.is_slanted by 18%
#259
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.
📄 18% (0.18x) speedup for
Char.is_slantedinlib/matplotlib/_mathtext.py⏱️ Runtime :
1.16 milliseconds→980 microseconds(best of63runs)📝 Explanation and details
This optimization implements attribute caching to eliminate repeated property lookups in the
is_slanted()method. The key change is cachingself._metrics.slantedasself._is_slantedduring initialization, then returning this cached value instead of accessing the attribute chain each time.Specific optimizations applied:
self._is_slanted = self._metrics.slantedin__init__()to cache the slanted property onceis_slanted()to return the cachedself._is_slantedinstead ofself._metrics.slantedWhy this leads to speedup:
In Python, attribute access through chains like
self._metrics.slantedinvolves multiple dictionary lookups and potential overhead if.slantedis implemented as a property with getter logic. By caching this value once during object creation, we eliminate:Performance characteristics from tests:
The optimization shows consistent 15-30% speedups across various scenarios, with particularly strong performance gains (20-33%) for:
The speedup is most beneficial when
is_slanted()is called frequently on the sameCharobjects, which appears to be the common usage pattern based on the 6,331 hits in the profiler results. Since the slanted property is determined at font metrics retrieval time and doesn't change during aCharobject's lifetime, this caching approach maintains correctness while providing meaningful performance improvements.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-Char.is_slanted-mjd0i9x1and push.