⚡️ Speed up method AgentUpdateRequest.serialize_model by 45%
#127
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.
📄 45% (0.45x) speedup for
AgentUpdateRequest.serialize_modelinsrc/mistralai/models/agentupdaterequest.py⏱️ Runtime :
137 microseconds→94.3 microseconds(best of67runs)📝 Explanation and details
The optimization achieves a 45% speedup by converting expensive O(n) list lookups to O(1) set operations and eliminating redundant computations:
Key Optimizations:
optional_fieldsandnullable_fieldsfrom lists to sets, transformingk in optional_fieldsfrom O(n) to O(1) operationsself.__pydantic_fields_set__.intersection({n})for each field (which creates a new set), the code now precomputesfields_setonce and uses directn in fields_setchecksval != UNSET_SENTINELtoval is not UNSET_SENTINEL, using identity comparison instead of equality comparison for the sentinel objectPerformance Impact:
The test results show consistent 27-56% improvements across all scenarios, with particularly strong gains for:
These optimizations are especially effective when processing objects with many fields but only a few set values, which appears to be the common use case for AgentUpdateRequest serialization.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-AgentUpdateRequest.serialize_model-mh4km42uand push.