⚡️ Speed up method Usage.__add__
by 290%
#21
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.
📄 290% (2.90x) speedup for
Usage.__add__
inpydantic_ai_slim/pydantic_ai/usage.py
⏱️ Runtime :
3.25 microseconds
→834 nanoseconds
(best of235
runs)📝 Explanation and details
REFINEMENT Here is an optimized version of your provided code.
Summary of speedups applied:
getattr
/setattr
: Use direct attribute access since field names are statically known, avoiding attribute lookup overhead.__add__
: Avoid slowcopy(self)
. Use direct construction, which is both faster and more memory-efficient for your dataclass.collections.Counter
if available to minimize key-by-key dict overhead (but without importing new modules if not already present, as none are imported in the original).All logic and return values remain identical.
Key optimizations.
incr
:__add__
:Usage
directly, calculating all fields in one step.details
, merges in minimal steps, using shallow.copy()
only as needed.This will notably reduce attribute lookup, dictionary calls, and avoid unnecessary copying for the common case. No external dependencies are used, and all comments are preserved unless a related section changed.
Your
Usage.__repr__
and type annotations remain as in the reference codebase and are consistent with this version.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-Usage.__add__-mddvpy23
and push.