⚡️ Speed up method Resources.components_for by 140%
#84
+8
−1
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.
📄 140% (1.40x) speedup for
Resources.components_forinsrc/bokeh/resources.py⏱️ Runtime :
511 microseconds→213 microseconds(best of250runs)📝 Explanation and details
The optimization replaces the inefficient list comprehension with membership testing against a list with a more efficient approach using set operations.
Key optimization: In the
components_formethod, instead of checkingcomp in self._component_defs[kind]for each component (which requires linear search through the list), the code now:kind_set = set(kind_comps)comp in kind_set(O(1) average case vs O(n) for list)kind_compsis emptyWhy this is faster: Set membership testing in Python is O(1) average case using hash lookups, while list membership testing is O(n) requiring linear scanning. For the filtering operation, this changes the overall complexity from O(n*m) to O(n+m) where n is the number of components and m is the size of the component definitions list.
Performance impact: The test results show this optimization is particularly effective for:
The optimization trades a small upfront cost of set creation for significant savings during the filtering loop, making it especially beneficial when
components_foris called with large component lists or frequently in performance-critical code paths.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-Resources.components_for-mhvdbgxrand push.