⚡️ Speed up method PrivacyService.is_policy_defined by 18%
#459
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.
📄 18% (0.18x) speedup for
PrivacyService.is_policy_definedinnvflare/private/privacy_manager.py⏱️ Runtime :
1.21 milliseconds→1.03 milliseconds(best of143runs)📝 Explanation and details
The optimization reduces redundant attribute lookups by storing
PrivacyService.managerin a local variable. In the original code,PrivacyService.manageris accessed twice - once in the condition check and again when callingis_policy_defined(). This requires two class attribute lookups, which are slower than local variable access in Python.The optimized version stores the attribute in a local variable
managerat the beginning, eliminating the second attribute lookup. The line profiler shows this reduces the per-hit time for the attribute access from 275.3ns to 259.4ns, and the method call from 612.4ns to 583.2ns.The optimization also removes the unnecessary
else:clause since the function returns early when the condition is met, slightly improving code flow but without significant performance impact.This optimization is particularly effective for test cases with valid managers (15-37% speedup) since they benefit most from the eliminated second attribute lookup. Cases with falsy managers see smaller gains (7-14%) since they only execute the first attribute access. The 17% overall speedup aligns well with the test results showing consistent improvements across all scenarios.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-PrivacyService.is_policy_defined-mhe0t67yand push.