⚡️ Speed up function validate_float by 25%
#123
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.
📄 25% (0.25x) speedup for
validate_floatinsrc/mistralai/utils/serializers.py⏱️ Runtime :
2.25 milliseconds→1.80 milliseconds(best of74runs)📝 Explanation and details
The optimization replaces
isinstance(f, (float, Unset))withisinstance(f, float) or f is Unset. This change achieves a 24% speedup by avoiding the costly tuple-based isinstance check.Key Changes:
fis an instance of eitherfloatorUnsetin a single call, the code now checks forfloatfirst, then uses identity comparison (is) forUnset.Unsetappears to be a singleton object (not a type), usingf is Unsetis both faster and more semantically correct thanisinstance(f, Unset).Why This is Faster:
isinstance(f, (float, Unset))creates a tuple and performs more complex type checking logic internally.oroperator allows early exit whenfis a float (the most common case), avoiding theUnsetcheck entirely.f is Unsetis a simple pointer comparison, much faster than isinstance checking.Performance Benefits by Test Case:
This optimization is particularly effective for workloads with many float inputs, as they benefit most from the short-circuit evaluation.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-validate_float-mh4iyb8dand push.