⚡️ Speed up method Representation.__repr_args__
by 31%
#44
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.
📄 31% (0.31x) speedup for
Representation.__repr_args__
inpydantic/_internal/_repr.py
⏱️ Runtime :
21.7 microseconds
→16.5 microseconds
(best of347
runs)📝 Explanation and details
To optimize the
Representation
class method__repr_args__
for improved performance, we can make the following changes.Avoid using intermediate lists.
Use dictionary access more efficiently.
.items()
method of the dictionary directly if__dict__
is available, instead of using.keys()
and thengetattr
.Here's the optimized code.
What was changed.
Efficient
__slots__
check.__slots__
is empty and branch directly whether to use__dict__
or__slots__
.Dictionary Access Optimization.
self.__dict__.items()
directly for name-value pairs, avoiding the need to get keys and fetch values individually.By condensing list creation steps, we reduce overhead and unnecessary iterations, making the function more efficient.
✅ Correctness verification report:
🌀 Generated Regression Tests Details
📢 Feedback on this optimization?