⚡️ Speed up method ModelSchema.to_dict
by 6%
#70
+2
−0
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.
📄 6% (0.06x) speedup for
ModelSchema.to_dict
inguardrails/classes/schema/model_schema.py
⏱️ Runtime :
156 microseconds
→147 microseconds
(best of56
runs)📝 Explanation and details
The optimization adds a simple early-return check for empty dictionaries before performing the dictionary comprehension. When
super().to_dict()
returns an empty dictionary, the optimized version immediately returns it without executing the comprehension{k: v for k, v in super_dict.items() if v is not None}
.Key optimization:
if not super_dict:
check avoids the overhead of creating a new dictionary and iterating through zero items when the parent'sto_dict()
returns an empty dict.Why this provides a speedup:
not super_dict
) is extremely fast - it just checks if the dict size is zeroPerformance characteristics based on test results:
The optimization maintains identical behavior while reducing unnecessary work when the input dictionary is empty.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-ModelSchema.to_dict-mh2o91jf
and push.