⚡️ Speed up function _get_state_name by 9%
#34
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.
📄 9% (0.09x) speedup for
_get_state_nameinoptuna/visualization/matplotlib/_timeline.py⏱️ Runtime :
1.10 milliseconds→1.01 milliseconds(best of162runs)📝 Explanation and details
The optimization achieves a 9% speedup through two key changes:
1. Variable caching: The optimized version stores
bar_info.statein a local variablestate, avoiding repeated attribute access. The line profiler shows this reduces the condition check from 391.9ns per hit to 230ns per hit (41% faster) because Python only needs to access thestateattribute once instead of twice.2. Identity comparison: Changed
bar_info.state == TrialState.COMPLETEtostate is TrialState.COMPLETE. Since enum members are singletons in Python, identity comparison (is) is faster than equality comparison (==) as it only checks object identity rather than invoking the__eq__method.3. Eliminated else clause: Removed the
else:statement, allowing the function to fall through to the return statement, which reduces branching overhead.The test results show consistent improvements across all scenarios:
These optimizations are particularly effective for high-frequency scenarios where this function is called repeatedly, as demonstrated by the large batch tests showing sustained performance gains.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_get_state_name-mhazl153and push.