⚡️ Speed up function _replacer by 73%
#406
Open
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.
📄 73% (0.73x) speedup for
_replacerinpandas/core/computation/scope.py⏱️ Runtime :
717 microseconds→415 microseconds(best of112runs)📝 Explanation and details
The optimization replaces exception handling with explicit type checking, delivering a 72% speedup by avoiding the performance penalty of Python's
try/exceptmechanism.Key changes:
try: ord(x) except TypeError: xwithif isinstance(x, int): x else: ord(x)xis already an integerWhy this is faster:
In Python, exception handling has significant overhead even when exceptions don't occur - the
tryblock setup itself costs time. The line profiler shows the original code spent 35.8% of time inord(x)and 15.2% handlingTypeError. The optimized version usesisinstance()which is a fast C-level type check, spending only 37.1% of time on type detection and 20.6% on the integer assignment.Performance characteristics:
isinstance()check before callingord()isinstance()vs exception handlingContext impact:
This function is called from
_raw_hex_id()which processes packed struct data (likely integers fromid()pointers). In typical usage, most inputs are integers from the packed bytes, making this optimization highly effective for the hot path while maintaining identical behavior and error handling.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_replacer-mj9uwdjaand push.