⚡️ Speed up function get_prediction_aip_http_port by 34%
#49
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.
📄 34% (0.34x) speedup for
get_prediction_aip_http_portingoogle/cloud/aiplatform/utils/prediction_utils.py⏱️ Runtime :
34.5 microseconds→25.8 microseconds(best of125runs)📝 Explanation and details
The optimization replaces the explicit
Nonecheck and length validation with a single truthiness test. The original code usesserving_container_ports is not None and len(serving_container_ports) > 0, which requires two separate evaluations: a None check and a length calculation. The optimized version usesif serving_container_ports:, which leverages Python's truthiness rules where empty sequences (lists, tuples) andNoneboth evaluate toFalse.This change eliminates the
len()function call, which has overhead even for small sequences, and reduces the boolean expression from two operations to one. The line profiler shows the conditional check time dropped from 64,650ns to 40,013ns (38% reduction), contributing significantly to the overall 33% speedup.The optimization is particularly effective for:
len()overhead becomes more significant with larger containersThe truthiness approach is idiomatic Python and maintains identical behavior - both
Noneand empty sequences return the default port, while non-empty sequences return their first element.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-get_prediction_aip_http_port-mglmrngqand push.