⚡️ Speed up function looks_like_url by 150%
#116
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.
📄 150% (1.50x) speedup for
looks_like_urlinpy-polars/src/polars/io/_utils.py⏱️ Runtime :
1.56 milliseconds→625 microseconds(best of117runs)📝 Explanation and details
The optimization pre-compiles the regex pattern into a module-level constant
_URL_REGEXinstead of compiling it on every function call. This eliminates the repeated regex compilation overhead that occurs each timelooks_like_url()is called.Key changes:
_URL_REGEX = re.compile(r"^(ht|f)tps?://", re.IGNORECASE)as a module-level constantre.match("^(ht|f)tps?://", path, re.IGNORECASE)to_URL_REGEX.match(path)Why this is faster:
Regular expression compilation is computationally expensive as it involves parsing the pattern, building a finite state machine, and optimizing it. In the original code, this compilation happens every single time the function is called. The optimized version compiles the regex once at module import time and reuses the compiled pattern object.
Performance characteristics:
This optimization provides consistent speedup across all test cases since every call benefits from avoiding regex recompilation. The 150% speedup (2.5x faster) is particularly significant for:
looks_like_url()is called multiple times during program executionThe optimization maintains identical functionality and correctness while dramatically reducing per-call overhead.
✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
🌀 Generated Regression Tests and Runtime
🔎 Concolic Coverage Tests and Runtime
To edit these changes
git checkout codeflash/optimize-looks_like_url-mgyzodqtand push.