⚡️ Speed up function fignum_exists by 7%
#252
Open
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.
📄 7% (0.07x) speedup for
fignum_existsinlib/matplotlib/pyplot.py⏱️ Runtime :
29.1 microseconds→27.2 microseconds(best of28runs)📝 Explanation and details
The optimization replaces a costly list-based membership check with an efficient set-based lookup for string figure identifiers in
fignum_exists().Key Change:
_figlabels_set()helper function that returns a set of figure labels instead of a sorted listfignum_exists()to use_figlabels_set()for string lookups instead ofget_figlabels()Why This Is Faster:
The original code called
get_figlabels()for string membership checks, which performed three expensive operations:num in get_figlabels()The optimized version uses
_figlabels_set()which:Performance Impact:
Behavior Preservation:
has_fignum)get_figlabels()maintains its sorted list contract for existing callersThis optimization is particularly beneficial when
fignum_exists()is called frequently with string identifiers, as it eliminates unnecessary sorting and improves lookup complexity from O(n) to O(1).✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
test_backend_bases.py::test_canvas_changetest_figure.py::test_fignum_exists🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-fignum_exists-mjah4kidand push.