⚡️ Speed up method Figure.add_sankey by 11%
#67
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.
📄 11% (0.11x) speedup for
Figure.add_sankeyinplotly/graph_objs/_figure.py⏱️ Runtime :
4.97 milliseconds→4.46 milliseconds(best of16runs)📝 Explanation and details
The optimization applies import caching to eliminate redundant module imports when
add_sankey()is called multiple times on the same Figure instance.Key Changes:
hasattr(self, "_Sankey_cls")to cache the importedSankeyclassplotly.graph_objs.Sankeyon the first call, storing it asself._Sankey_clsWhy This is Faster:
In Python,
importstatements have overhead even when the module is already loaded, as the interpreter must resolve the module path and perform namespace lookups. By caching the class reference, we avoid this repeated import cost.Performance Profile:
from plotly.graph_objs import Sankey) went from ~3.0ms to ~1.6ms total time across all callsThis optimization is particularly valuable for applications that programmatically generate many Sankey diagrams or add multiple Sankey traces to the same figure, as demonstrated by the 11.8% speedup in the large multiple traces test case.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-Figure.add_sankey-mhfv84hyand push.