⚡️ Speed up method ToolManager.list_tools by 48%
#6
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.
📄 48% (0.48x) speedup for
ToolManager.list_toolsinsrc/mcp/server/fastmcp/tools/tool_manager.py⏱️ Runtime :
2.92 microseconds→1.97 microseconds(best of43runs)📝 Explanation and details
Here is a faster rewrite of your original program. The major cost in your line profile is
list(self._tools.values()). Since the number of tools is likely not huge and Python dict objects'.values()view is already very fast, the only realistic optimization possible here is to avoid actually copying into a list whenever possible.If you need a
listin all usages (due to downstream mutation that requires a real list), you cannot easily optimize this. But if this function frequently gets called just to iterate or to check membership/length etc, and you control the code that consumes it, returning a view (using.values()) will be strictly faster and more memory efficient (no copy).However, if you must keep returning a list (as per signature) for compatibility, the only microscopic improvement is to reuse an existing list, or to avoid even that call in the "empty" case. Otherwise, list conversion is already C speed.
Below is as optimized as possible, with a micro-optimization for the empty-dictionary case (most significant for very frequent calls with often no tools).
Summary:
There is no further real-world optimization possible unless you are allowed to change the interface (to return a view or a tuple), or you cache the list and invalidate on mutation (which is rarely worth it for such a quick operation). If your actual bottleneck is somewhere else (such as tool registration, not listing), consider profiling those paths as well.
✅ Correctness verification report:
🌀 Generated Regression Tests Details
To edit these changes
git checkout codeflash/optimize-ToolManager.list_tools-ma2ynxrpand push.