⚡️ Speed up method Figure.add_parcats by 5%
#66
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.
📄 5% (0.05x) speedup for
Figure.add_parcatsinplotly/graph_objs/_figure.py⏱️ Runtime :
84.9 milliseconds→80.5 milliseconds(best of5runs)📝 Explanation and details
The optimized code achieves a 5% speedup through two key changes:
1. Import Optimization: The
Parcatsimport is moved from inside theadd_parcatsmethod to the module level (from plotly.graph_objs import Parcats). This eliminates the repeated import overhead that occurred every timeadd_parcatswas called, which the line profiler shows took ~15ms per call in the original version.2. Direct Method Call: Both
add_traceand the final call inadd_parcatsnow useBaseFigure.add_trace()directly instead ofsuper().add_trace()orself.add_trace(). This bypasses Python's method resolution overhead by avoiding the dynamic lookup through the inheritance chain.Why this works: Python's
super()and method resolution require runtime lookups to determine which method to call in the inheritance hierarchy. By callingBaseFigure.add_trace()directly, we eliminate this lookup cost. The import optimization is particularly effective for methods called frequently, as seen in test cases like "many traces" (19.6% faster) and scenarios with multipleadd_parcatscalls.Best performance gains: The optimizations show the most benefit in scenarios with multiple trace additions, error handling paths (where early exits avoid the full method overhead), and repeated calls to
add_parcats. Single-call scenarios see smaller but consistent improvements around 5-20% faster.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-Figure.add_parcats-mhful0m5and push.