From a19552e866e3daf6f5e752720948698838d2e775 Mon Sep 17 00:00:00 2001 From: "codeflash-ai[bot]" <148906541+codeflash-ai[bot]@users.noreply.github.com> Date: Sat, 1 Nov 2025 16:19:52 +0000 Subject: [PATCH] Optimize figure_rst 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:** - **Replaced list comprehension with generator**: Instead of creating a full list with `[... 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 with `next()`. **Why this is faster:** - The original code processes **all** figures in `figure_list` upfront, even though only the first one is ever used. This is evident from the line profiler showing 99.7% of time spent building the complete `figure_paths` list. - The optimized version processes figures **lazily** - it only computes the path transformation for the first figure and stops immediately. **Performance impact by test case:** - **Massive gains for large lists**: Tests with 1000+ figures show 21,556% to 29,717% speedups because the optimization avoids processing 999+ unnecessary items - **Small overhead for single items**: Tests with single figures show 1-7% slowdown due to the try/except overhead, but this is negligible compared to the gains for larger lists - **Empty lists**: Slight overhead (28-29% slower) due to exception handling vs simple boolean check 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. --- plotly/io/_sg_scraper.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/plotly/io/_sg_scraper.py b/plotly/io/_sg_scraper.py index af15b7d1c33..5bd3ce2e078 100644 --- a/plotly/io/_sg_scraper.py +++ b/plotly/io/_sg_scraper.py @@ -81,14 +81,16 @@ def figure_rst(figure_list, sources_dir): rst code to embed the images in the document """ - figure_paths = [ + figure_paths_iter = ( os.path.relpath(figure_path, sources_dir).replace(os.sep, "/").lstrip("/") for figure_path in figure_list - ] + ) images_rst = "" - if not figure_paths: + try: + figure_name = next(figure_paths_iter) + except StopIteration: return images_rst - figure_name = figure_paths[0] + figure_path = os.path.join("images", os.path.basename(figure_name)) images_rst = SINGLE_HTML % figure_path return images_rst