⚡️ Speed up function _use_widgets by 13%
#68
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.
📄 13% (0.13x) speedup for
_use_widgetsinsrc/bokeh/embed/bundle.py⏱️ Runtime :
2.00 milliseconds→1.77 milliseconds(best of44runs)📝 Explanation and details
The optimization achieves a 12% speedup by replacing Python's built-in
any()function with explicitforloops that enable early returns.Key changes:
Eliminated generator overhead in
_any(): Replacedany(query(x) for x in objs)with a direct for loop that returnsTrueimmediately upon finding a match. This avoids creating a generator object and the overhead of theany()builtin.Direct widget checking in
_use_widgets(): Instead of using the_any()helper with a lambda, the optimized version loops directly through objects and checksisinstance(obj, Widget), returningTrueon first match. This eliminates function call overhead and lambda creation.Preserved import location: The
Widgetimport remains inside the function (not moved outside as mentioned in comments), maintaining the original lazy import behavior.Why this works:
_any()and creating lambda functionsPerformance characteristics by test case:
The optimization is most effective when widgets are found early in the iteration or when avoiding the overhead of
any()and generators provides measurable benefit.✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
unit/bokeh/embed/test_bundle.py::Test__use_widgets.test_with_widgetsunit/bokeh/embed/test_bundle.py::Test__use_widgets.test_without_widgets🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_use_widgets-mhb6o9b3and push.