⚡️ Speed up function repeat by 12%
#141
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.
📄 12% (0.12x) speedup for
repeatinsrc/bokeh/driving.py⏱️ Runtime :
17.0 microseconds→15.2 microseconds(best of250runs)📝 Explanation and details
The optimized code achieves a 12% speedup through two key micro-optimizations that reduce function call overhead and variable lookup costs:
Key Optimizations:
Direct method binding in
force(): Replacednext(sequence)withsequence.__next__()by storing a local referencenext_sequence = sequence.__next__. This eliminates the global lookup for thenextbuiltin function and removes one layer of function call indirection, providing faster access in tight loops.Closure variable optimization in
repeat(): Changed the inner functionffrom a closure that capturessequenceandNto using default argumentsf(i: int, sequence=sequence, N=N). This is significantly faster because accessing default arguments is cheaper than dereferencing closure cells in Python.Performance Impact:
The line profiler shows the optimizations are most effective in the hot path - the
yield f(i)line in_advance()which accounts for ~57% of total execution time. Since this line is called thousands of times (3,565 hits in the profile), even small per-call improvements compound significantly.Test Case Analysis:
The optimizations particularly benefit scenarios with:
test_repeat_large_scale_long_run(1000 iterations) andtest_repeat_large_scale_performancesee the most benefitThe changes preserve all functionality and behavior - the optimizations are purely performance-focused micro-optimizations that leverage Python's internal implementation details for faster variable access patterns.
✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
unit/bokeh/test_driving.py::test_repeat🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-repeat-mhwjpz7qand push.