From d96ad846e190c32b916afa2b7045fbe69daa4cd7 Mon Sep 17 00:00:00 2001 From: "codeflash-ai[bot]" <148906541+codeflash-ai[bot]@users.noreply.github.com> Date: Thu, 13 Nov 2025 02:50:35 +0000 Subject: [PATCH] Optimize AltairPlot.create_legend The optimization achieves a **30% speedup** by eliminating unnecessary dictionary operations and intermediate variable assignments. **Key optimizations:** 1. **Early returns**: Instead of storing values in a `legend` variable and returning at the end, the optimized code returns immediately when conditions are met, reducing variable assignments and memory operations. 2. **Eliminated dictionary unpacking**: The original code created an intermediate dictionary `{"orient": position} if position else {}` and then unpacked it with `**position`. The optimized version directly constructs the final dictionary in one operation, avoiding the creation and unpacking of temporary objects. 3. **Reduced branching complexity**: The original code used a ternary operator within dictionary unpacking, while the optimized version uses clearer conditional statements that allow for more efficient execution paths. **Performance impact by test case:** - **"none" position cases**: 5-13% improvement due to early return eliminating unnecessary variable assignments - **Valid position cases**: 20-37% improvement from avoiding dictionary creation/unpacking overhead - **Empty/falsy position cases**: 28-36% improvement as these benefit most from skipping the intermediate dictionary operations - **Large-scale tests**: Consistent 30%+ improvements, showing the optimization scales well The line profiler shows the optimization eliminates the costly `**position` unpacking operation (25.3% of original runtime) and reduces dictionary creation overhead. Since this function appears to be used for UI legend generation, the performance gains would be particularly beneficial in interactive applications where legends are frequently created or updated. --- gradio/components/plot.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/gradio/components/plot.py b/gradio/components/plot.py index cb92b97f9a..cda380762e 100644 --- a/gradio/components/plot.py +++ b/gradio/components/plot.py @@ -154,12 +154,12 @@ class AltairPlot: @staticmethod def create_legend(position, title): if position == "none": - legend = None - else: - position = {"orient": position} if position else {} - legend = {"title": title, **position} + return None + + if not position: + return {"title": title} - return legend + return {"title": title, "orient": position} @staticmethod def create_scale(limit):