⚡️ Speed up function validate_decimal by 35%
#122
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.
📄 35% (0.35x) speedup for
validate_decimalinsrc/mistralai/utils/serializers.py⏱️ Runtime :
1.66 milliseconds→1.23 milliseconds(best of67runs)📝 Explanation and details
The optimized code achieves a 35% speedup by replacing expensive
isinstance()calls with faster type checking strategies:Key optimizations:
Pre-computed type tuples: Moved
(Decimal, Unset)and(str, int, float)outside the function to avoid recreating them on every call.Direct type comparison for common cases: Uses
type(d) is Decimalandtype(d) is Unsetinstead ofisinstance()for exact type matching, which bypasses the overhead of inheritance hierarchy checks.Fast-path for built-in types: Uses
type(d) in _STR_INT_FLOAT_TYPESfor quick membership testing against the pre-computed tuple of common types.Fallback isinstance() checks: Maintains backward compatibility by keeping
isinstance()checks as fallbacks to handle edge cases like subclasses.Why it's faster:
isinstance()is expensive because it checks the entire class hierarchy (MRO)type(d) is Xonly does a single pointer comparisontype(d) in tupleis faster thanisinstance(d, tuple)for exact type matchesPerformance by test case type:
"123","0.0"benefit most from the fast-path type checkingThe optimization maintains identical behavior while dramatically improving the common-case performance.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-validate_decimal-mh4is4svand push.