⚡️ Speed up function _get_adc_environment_variable
by 5%
#41
+5
−1
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.
📄 5% (0.05x) speedup for
_get_adc_environment_variable
ingoogle/cloud/aiplatform/docker_utils/run.py
⏱️ Runtime :
41.2 microseconds
→39.2 microseconds
(best of219
runs)📝 Explanation and details
The optimization achieves a 5% speedup through two key changes:
1. Inlined constant definition: The
_ADC_ENVIRONMENT_VARIABLE
constant is now defined locally instead of being imported from elsewhere. This eliminates the overhead of import lookup and module attribute access during function calls.2. EAFP (Easier to Ask for Forgiveness than Permission) pattern: Replaced
os.environ.get()
with direct dictionary accessos.environ[key]
wrapped in try/except. This is faster for the common case where the environment variable exists because:os.environ[key]
performs a single hash table lookupos.environ.get(key)
internally does the same lookup plus additional default value handling logicThe line profiler shows the optimized version spends 87.4% of time on the successful lookup (vs 100% in the original), with minimal overhead for the exception handling path (only 2.3% total for KeyError cases).
Test case performance: The optimization is most effective when the environment variable is present (1-12% faster across most test cases), with smaller gains or slight regressions when the variable is missing, which aligns with the EAFP optimization strategy that prioritizes the success path.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_get_adc_environment_variable-mgklw78k
and push.