⚡️ Speed up function _is_reverse_scale by 30%
#154
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.
📄 30% (0.30x) speedup for
_is_reverse_scaleinoptuna/visualization/_utils.py⏱️ Runtime :
1.70 milliseconds→1.31 milliseconds(best of165runs)📝 Explanation and details
The optimization achieves a 29% speedup by making two key changes:
Pre-caching the enum value:
_MINIMIZE = StudyDirection.MINIMIZEis computed once at import time, eliminating repeated attribute lookups toStudyDirection.MINIMIZEon every function call.Identity comparison instead of equality: Changed
study.direction == StudyDirection.MINIMIZEtostudy.direction is _MINIMIZE. Theisoperator performs a fast pointer/identity check rather than invoking the==method, which can involve more overhead for enum comparisons.Why this works: Python's
isoperator is one of the fastest comparison operations since it only checks if two variables reference the same object in memory. By pre-caching the enum value, we guarantee the identity check will work correctly while avoiding both attribute access overhead and equality method dispatch.Performance impact by test case: The optimization shows particularly strong gains (40-77% faster) when the comparison needs to evaluate the
study.directioncheck - especially in cases with non-MINIMIZE directions or unusual direction values. When short-circuiting occurs (target is not None), gains are smaller (0-10%) since the second part of the OR expression isn't reached.Scale benefits: The optimization shines in high-frequency scenarios, as shown by the large-scale tests where 1000 iterations see 28-46% improvements. Since this is likely a utility function called frequently during optimization runs, these micro-optimizations compound significantly.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_is_reverse_scale-mho8igqiand push.