⚡️ Speed up function get_type_for_field by 117% in PR #4019 (fix-ruff-py310)
#4023
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.
⚡️ This pull request contains optimizations for PR #4019
If you approve this dependent PR, these changes will be merged into the original PR branch
fix-ruff-py310.📄 117% (1.17x) speedup for
get_type_for_fieldinstrawberry/experimental/pydantic/object_type.py⏱️ Runtime :
826 microseconds→381 microseconds(best of73runs)📝 Explanation and details
The optimization introduces a fast-path check that avoids expensive type reconstruction when recursive type processing doesn't actually change any type arguments.
Key optimization:
converted == orig_args(reference equality check). If the processed arguments are identical to the original ones, it returns the existingreplaced_typeimmediately instead of creating new type objects.Why this is faster:
copy_with()calls: The original code unconditionally calledreplaced_type.copy_with(converted)which creates new type objects even when no changes occurred. This operation dominated 45.6% of the original runtime.==) efficiently detects when no actual transformation occurred during recursion.Performance gains by test case type:
copy_with()when inner types don't changeThe optimization is most effective for type hierarchies with many unchanged leaf nodes, which is common in real-world Pydantic schemas.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-pr4019-2025-10-12T14.23.40and push.