⚡️ Speed up method FontProperties.copy by 432%
#220
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.
📄 432% (4.32x) speedup for
FontProperties.copyinlib/matplotlib/font_manager.py⏱️ Runtime :
232 microseconds→43.6 microseconds(best of67runs)📝 Explanation and details
The optimized
copymethod replaces the genericcopy.copy(self)call with a direct, manual instance creation approach. This provides a 431% speedup by avoiding the overhead of Python's copy module machinery.Key optimization changes:
cls.__new__(cls)instead of relying oncopy.copy()result.__dict__ = self.__dict__.copy()Why this is faster:
The
copy.copy()function performs type introspection, checks for special copy methods, and uses a general-purpose copying strategy. For simple objects likeFontPropertiesthat only contain basic attributes, this overhead is unnecessary. The optimized version bypasses all this machinery by directly creating a new instance and shallow-copying the attribute dictionary.Performance characteristics from tests:
__dict__.copy()approach provides the same shallow copy semantics as the originalWorkload impact:
Since
FontPropertiesobjects are likely created and copied frequently in matplotlib's text rendering pipeline, this optimization could provide meaningful performance improvements in applications that render lots of text with varying font properties, especially in plotting libraries where font copying might occur in tight loops during layout calculations.The optimization preserves all original behavior including shallow copy semantics for mutable attributes like family lists.
✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-FontProperties.copy-miy8owsqand push.