⚡️ Speed up function make_globally_unique_css_safe_id by 51%
#63
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.
📄 51% (0.51x) speedup for
make_globally_unique_css_safe_idinsrc/bokeh/util/serialization.py⏱️ Runtime :
542 milliseconds→358 milliseconds(best of23runs)📝 Explanation and details
The optimization achieves a 51% speedup by eliminating two major performance bottlenecks:
1. Eliminated repeated import overhead: The original code performed
from ..core.types import IDinside each function call, which was extremely expensive (18.2% of runtime inmake_globally_unique_id). The optimized version moves this to a module-level import as_ID, avoiding the repeated import cost entirely.2. Reduced unnecessary object creation in the retry loop: In
make_globally_unique_css_safe_id(), the original code calledmake_globally_unique_id()for each retry attempt, creating anIDobject each time only to discard it if the first character wasn't alphabetic. The optimized version generatesstr(uuid.uuid4())directly in the loop and only creates theIDobject when a valid string is found.These changes are particularly effective for the common case where UUID strings start with a digit (requiring retries). The profiler shows the loop in
make_globally_unique_css_safe_id()runs ~100x per call on average, making the per-iteration savings compound significantly. All test cases show consistent ~50% speedup, indicating the optimization benefits both single calls and batch operations equally.The behavior remains identical - same return types, same CSS-safety guarantees, same fallback to "bk-" prefix when needed.
✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-make_globally_unique_css_safe_id-mhb3b336and push.