⚡️ Speed up method ArgModelBase.model_dump_one_level by 340%
#5
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.
📄 340% (3.40x) speedup for
ArgModelBase.model_dump_one_levelinsrc/mcp/server/fastmcp/utilities/func_metadata.py⏱️ Runtime :
78.5 microseconds→17.9 microseconds(best of215runs)📝 Explanation and details
Here is an optimized version of your program.
The original code loops over
self.__class__.model_fields.keys()and usesgetattr(self, field_name).This can be optimized by directly using
self.__dict__to avoid the attribute lookup overhead in a tight loop.This will also avoid creating a new dict and inserting keys one by one.
Optimized code:
Key Points:
self.__dict__contains the model's fields and their current values.self.__dict__.copy()returns a shallow copy, matching your original behavior (returns a new dict).getattrand looping through the keys.Behavior is the same as before, just much more efficient!
✅ Correctness verification report:
🌀 Generated Regression Tests Details
To edit these changes
git checkout codeflash/optimize-ArgModelBase.model_dump_one_level-ma2y3jb1and push.