⚡️ Speed up function figure_rst by 2,342%
#90
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.
📄 2,342% (23.42x) speedup for
figure_rstinplotly/io/_sg_scraper.py⏱️ Runtime :
15.7 milliseconds→644 microseconds(best of115runs)📝 Explanation and details
The optimized code achieves a 2341% speedup by replacing an expensive list comprehension with a lazy generator approach when only the first element is needed.
Key optimization:
[... for figure_path in figure_list], the code now uses a generator expression(... for figure_path in figure_list)and extracts only the first item withnext().Why this is faster:
figure_listupfront, even though only the first one is ever used. This is evident from the line profiler showing 99.7% of time spent building the completefigure_pathslist.Performance impact by test case:
This optimization is particularly effective for the function's actual usage pattern where only the first figure matters, making it scale O(1) instead of O(n) with respect to list size.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-figure_rst-mhghmshvand push.