⚡️ Speed up method ParserState.copy by 383%
#261
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.
📄 383% (3.83x) speedup for
ParserState.copyinlib/matplotlib/_mathtext.py⏱️ Runtime :
331 microseconds→68.5 microseconds(best of155runs)📝 Explanation and details
The optimization replaces the generic
copy.copy(self)call with a direct constructor callParserState(self.fontset, self._font, self.font_class, self.fontsize, self.dpi), achieving a 382% speedup.Key Performance Improvement:
copy.copy()introducesWhy This Works:
The
copy.copy()function performs a generic shallow copy by inspecting the object's__dict__and recreating it, which involves:__new____dict__manipulationThe direct constructor approach bypasses this overhead by explicitly passing the five simple attributes (
fontset,_font,font_class,fontsize,dpi) directly to__init__.Test Results Analysis:
All test cases show consistent 6-7x speedup (600-750% faster), with particularly strong performance on:
The optimization maintains identical shallow copy semantics - the
fontsetobject reference is still shared between original and copy, ensuring behavioral compatibility. This makes it an ideal drop-in replacement that preserves the expected shallow copy behavior while dramatically improving performance for this frequently-used parser state management operation.✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
test_textpath.py::test_copy🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-ParserState.copy-mjd1itzvand push.