⚡️ Speed up function bounce by 18%
#139
Open
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.
📄 18% (0.18x) speedup for
bounceinsrc/bokeh/driving.py⏱️ Runtime :
21.9 microseconds→18.6 microseconds(best of250runs)📝 Explanation and details
The optimization applies a closure variable optimization to the inner function
fwithin thebouncefunction. The key change is in the function definition:What changed:
Why this is faster:
In Python, variable lookups follow the LEGB rule (Local, Enclosing, Global, Built-in). The original code requires
fto accessNandsequencefrom the enclosing scope (closure variables) on every call. The optimized version captures these values as default arguments, making them local variables instead.Local variable access is significantly faster than closure variable access because:
fis called within the generatorPerformance impact:
The line profiler shows the optimization reduces time spent in the
_advancefunction'syield f(i)line from 9744ns to 7684ns per hit (21% improvement in the hottest line). The overall speedup of 17% demonstrates this micro-optimization's effectiveness whenfis called repeatedly.Test case analysis:
The optimization particularly benefits test cases that call the bounce driver many times (like
test_bounce_many_stepswith 1000 steps andtest_bounce_performance_large_steps), where the cumulative effect of faster variable lookups becomes significant. Single-call tests see minimal benefit, but high-frequency usage scenarios get substantial performance gains.✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
unit/bokeh/test_driving.py::test_bounce🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-bounce-mhwixv2qand push.