⚡️ Speed up method ResourceTemplate.from_function by 19%
#2
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
ResourceTemplate.from_functioninsrc/mcp/server/fastmcp/resources/templates.py⏱️ Runtime :
420 milliseconds→351 milliseconds(best of19runs)📝 Explanation and details
Here is an optimized version of your
ResourceTemplate.from_functionmethod.Key optimizations.
fn.__doc__and"text/plain"repeatedly inside the return statement by computing all needed default/fallback values before the object construction.validate_call(fn)if needed, assigning directly otherwise.TypeAdapter(fn).json_schema(), which is intrinsic to extracting the schema; there's no faster way using Pydantic v2, so this is kept but put as early as possible to fail fast.All comments are preserved (except where lines have been improved/clarified).
Net result:
If you need further runtime gains, consider caching the result of
TypeAdapter(fn)at a higher level if you'll be constructing many templates for the same function object(s). Otherwise, this is already approaching the limits given the dependence on Pydantic's dynamic typing machinery.✅ Correctness verification report:
🌀 Generated Regression Tests Details
To edit these changes
git checkout codeflash/optimize-ResourceTemplate.from_function-ma2x6cycand push.