⚡️ Speed up method AudioTranscriptionRequestStream.serialize_model by 14%
#128
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.
📄 14% (0.14x) speedup for
AudioTranscriptionRequestStream.serialize_modelinsrc/mistralai/models/audiotranscriptionrequeststream.py⏱️ Runtime :
307 microseconds→269 microseconds(best of108runs)📝 Explanation and details
The optimized code achieves a 14% speedup by making three key data structure optimizations:
Lists to Sets conversion: Changed
optional_fields,nullable_fields, andnull_default_fieldsfrom lists to sets. This converts membership tests (k in optional_fields) from O(n) linear searches to O(1) constant-time lookups, which is particularly beneficial when checking multiple field memberships in the loop.Direct set membership test: Replaced
self.__pydantic_fields_set__.intersection({n})withn in self.__pydantic_fields_set__. The original creates a temporary set and performs an intersection operation for each field, while the optimized version uses a direct membership test - much more efficient for single-element checks.Removed unnecessary pop operation: Eliminated
serialized.pop(k, None)since the popped value wasn't used. This removes an O(n) dictionary operation per field iteration.The test results show consistent improvements across all scenarios, with particularly strong gains (20-24%) in cases with multiple optional/nullable fields where the membership tests are performed more frequently. These optimizations are most effective for models with many optional fields, as the serialization logic performs multiple containment checks per field during the iteration loop.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-AudioTranscriptionRequestStream.serialize_model-mh4lea0fand push.