⚡️ Speed up method CanonicalStrategy._is_standalone_structural_token by 19%
#317
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.
📄 19% (0.19x) speedup for
CanonicalStrategy._is_standalone_structural_tokeninpython/sglang/srt/parser/harmony_parser.py⏱️ Runtime :
1.14 milliseconds→961 microseconds(best of221runs)📝 Explanation and details
The optimization replaces a costly O(n) list lookup with an O(1) set lookup by pre-computing a set of structural tokens during initialization.
Key Changes:
self._structural_tokens_set = set(self.guard_tokens)in__init__()to create a hash set from the token liststructural_tokens = [...]that occurred on every function callcontent_stripped in structural_tokens(O(n) list scan) tocontent.strip() in self._structural_tokens_set(O(1) hash lookup)Why This Is Faster:
Performance Impact:
The optimization delivers consistent 12-67% speedups across all test scenarios, with particularly strong gains for:
This optimization is especially valuable for parsing workloads where
_is_standalone_structural_tokenis called frequently, as the constant-time lookup scales much better than linear search as call frequency increases.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
🔎 Concolic Coverage Tests and Runtime
To edit these changes
git checkout codeflash/optimize-CanonicalStrategy._is_standalone_structural_token-mhoosu6vand push.