⚡️ Speed up function bokeh_repr by 33%
#16
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.
📄 33% (0.33x) speedup for
bokeh_reprinpanel/io/model.py⏱️ Runtime :
419 microseconds→316 microseconds(best of113runs)📝 Explanation and details
The optimization achieves a 32% speedup by eliminating repeated import overhead through import caching.
Key optimization:
Viewableon every function call (line profiler shows 194,845ns spent on import across 40 calls). The optimized version caches the import using function attributes - importing only once and storingViewableasbokeh_repr._viewablefor subsequent calls.Performance impact:
The line profiler clearly shows the difference:
from ..viewable import Viewableacross 40 callsWhy this works:
Python imports involve module lookup, loading, and namespace operations. By caching the imported class as a function attribute, we avoid this overhead on subsequent calls while maintaining the same functionality.
Test case benefits:
The optimization is particularly effective for:
The caching approach preserves all original behavior while dramatically reducing the most expensive operation in the function's hot path.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-bokeh_repr-mha36pyfand push.