⚡️ Speed up function _map_usage
by 42%
#29
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.
📄 42% (0.42x) speedup for
_map_usage
inpydantic_ai_slim/pydantic_ai/models/anthropic.py
⏱️ Runtime :
41.7 microseconds
→29.2 microseconds
(best of205
runs)📝 Explanation and details
REFINEMENT Here is an optimized version of your code, focusing on fast type checks, avoiding unnecessary dictionary comprehensions, and minimizing lookups and function calls. Key changes.
type()
comparisons for faster type matching, since you have a closed set of classes (much faster thanisinstance()
for known exact types based on the hit profile; works if no complex inheritance).details
dict in advance)..model_dump()
unless there's a usage dict (model_dump()
can be expensive).get
calls.All doc/comments preserved, only changed if code was altered.
Why is this faster?
type()
checks outperformisinstance
in predictable code paths with a fixed set of input types (as profiled, these are from a controlled API)..get()
or.model_dump()
or comprehension unless there's valid usage data.If you must support subclassing, use
isinstance()
; otherwise, the above will be highest performing for this workload.✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
models/test_anthropic.py::test_usage
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_map_usage-mdexafbs
and push.