⚡️ Speed up function _is_essential_tool by 114%
#1088
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.
📄 114% (1.14x) speedup for
_is_essential_toolinbackend/python/app/modules/agents/qna/tool_registry.py⏱️ Runtime :
1.49 milliseconds→698 microseconds(best of171runs)📝 Explanation and details
The optimized code achieves a 113% speedup through two key micro-optimizations:
1. Tuple vs List Allocation
["calculator.", "web_search", "get_current_datetime"]to a tuple literal("calculator.", "web_search", "get_current_datetime")2. Early-Exit Loop vs Generator Expression
any(pattern in full_tool_name for pattern in essential_patterns)with an explicitforloop that returnsTrueimmediately upon finding a matchany()line consumed 86.3% of total time, while the optimized loop distributes more efficiently across multiple linesPerformance Context
Based on
function_references, this function is called from_should_include_tool()as a fallback when user preferences don't explicitly include a tool. While not in the hottest path, the function is called frequently enough (3,076 hits in profiler) that these micro-optimizations compound meaningfully.Test Case Performance
The optimization shows consistent 60-190% speedups across all test scenarios, with particularly strong gains for:
The changes preserve all behavior while making the function more efficient for this specific use case of checking a small, fixed set of patterns.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_is_essential_tool-mja4zi8pand push.