⚡️ Speed up method UniversalBaseModel.model_construct by 139%
#115
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.
📄 139% (1.39x) speedup for
UniversalBaseModel.model_constructinskyvern/client/core/pydantic_utilities.py⏱️ Runtime :
28.2 milliseconds→11.8 milliseconds(best of77runs)📝 Explanation and details
The optimized code achieves a 139% speedup through three key optimizations that reduce redundant function calls and improve type checking efficiency:
1. Single Type Origin Calculation
The original code repeatedly called
typing_extensions.get_origin(clean_type)for each type check (Dict, List, Set, Sequence, Union), resulting in expensive introspection overhead. The optimized version calculatesoriginonce and reuses it throughout, eliminating redundant calls that were consuming ~25% of the function's runtime based on the profiler data.2. Set-Based Type Membership Checks
Instead of multiple
or-chained comparisons likeorigin == typing.Dict or origin == dict or clean_type == typing.Dict, the code now uses efficient set membership:origin in {dict, typing.Dict} or clean_type in {dict, typing.Dict}. This reduces the number of equality operations and makes type detection faster, especially for the commonly-used container types.3. Eliminated Redundant Processing in
constructMethodThe critical optimization removes the duplicate call to
convert_and_respect_annotation_metadatain theconstructmethod. The original code called this expensive function twice - once inmodel_constructand again inconstruct- effectively doubling the conversion overhead. The optimized version passes**valuesdirectly to the parent constructor after the initial conversion, cutting the function's execution time by ~80%.Performance Impact by Test Case:
The optimization is particularly effective for Pydantic model construction workflows where
convert_and_respect_annotation_metadataprocesses complex type annotations - a common pattern in API serialization libraries like this one.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-UniversalBaseModel.model_construct-mireyo7oand push.