⚡️ Speed up method Seq._is_seq by 29%
#135
Open
+20
−4
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.
📄 29% (0.29x) speedup for
Seq._is_seqinsrc/bokeh/core/property/container.py⏱️ Runtime :
891 microseconds→692 microseconds(best of192runs)📝 Explanation and details
The optimization restructures the type checking logic in
_is_seqand_is_seq_likemethods to achieve a 28% speedup by reducing unnecessary expensive operations.Key optimizations:
Fast string rejection in
_is_seq: Instead of evaluating a complex boolean expression withisinstance(value, str)at the end, the optimized version checks for strings first and returnsFalseimmediately. This eliminates the need to evaluateisinstance(value, Sequence)or call_is_seq_like()for the common case of string inputs.Early exit pattern: The optimized version uses early returns (
if isinstance(value, str): return False) rather than a single complex boolean expression, allowing the CPU to skip subsequent checks when earlier conditions are met.Reordered checks in
_is_seq_like: Thehasattr(value, "__getitem__")check is moved first because it's the fastest operation and rules out most non-sequence types (like sets) immediately. Theisinstance(value, Mapping)check follows, avoiding expensive MRO traversal when__getitem__isn't even present.Why this is faster:
isinstancecalls: String inputs (which are common based on test cases) now only require oneisinstancecheck instead of potentially three.hasattr, thenisinstance(Mapping)) happen first, filtering out most cases before the more expensiveisinstance(Container, Sized, Iterable)check.Performance gains by test case type:
_is_seq_likeThe optimization maintains identical behavior while significantly reducing computational overhead for the most common rejection cases.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-Seq._is_seq-mhwhbouyand push.