⚡️ Speed up function is_prebuilt_prediction_container_uri by 52%
#46
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.
📄 52% (0.52x) speedup for
is_prebuilt_prediction_container_uriingoogle/cloud/aiplatform/helpers/container_uri_builders.py⏱️ Runtime :
2.34 milliseconds→1.54 milliseconds(best of245runs)📝 Explanation and details
The optimization precompiles the regex pattern at module import time instead of recompiling it on every function call.
Key Change:
_CONTAINER_URI_REGEX = re.compile(prediction.CONTAINER_URI_REGEX)at module levelre.fullmatch(prediction.CONTAINER_URI_REGEX, image_uri)to_CONTAINER_URI_REGEX.fullmatch(image_uri)Why It's Faster:
Python's
re.fullmatch()with a string pattern internally compiles the regex on every call, which is expensive. By precompiling the regex once at import time, each function call skips the compilation step and directly uses the compiled pattern object. The line profiler shows the per-hit time dropped from 1961ns to 614ns (68% improvement per call).Performance Benefits:
This optimization excels in scenarios with repeated calls to the same function, which is evident in the test results:
The 51% overall speedup demonstrates that regex compilation was a significant bottleneck, making this a highly effective optimization for any code path that validates container URIs repeatedly.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-is_prebuilt_prediction_container_uri-mglkk5rland push.