⚡️ Speed up method Stack.peek by 14%
#144
Open
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.
📄 14% (0.14x) speedup for
Stack.peekinsrc/dsa/various.py⏱️ Runtime :
12.2 microseconds→10.7 microseconds(best of795runs)📝 Explanation and details
The optimization reorders the conditional logic in the
peek()method by checking for the empty stack case first. Instead ofif self.stack:followed by the return statement, it usesif not self.stack:to handle the empty case immediately and returnNone.Key optimization: This eliminates redundant truthiness evaluation for non-empty stacks. In the original code, Python evaluates
self.stackas truthy, then executes the return statement. In the optimized version, when the stack has elements, Python evaluatesnot self.stackas falsy and jumps directly to the return statement, avoiding the extra conditional branch.Why it's faster: The optimization reduces the number of operations for the common case (non-empty stacks). The line profiler shows that non-empty stack access (
return self.stack[0]) dropped from 682.9ns per hit to 585.4ns per hit - a significant improvement in the hot path.Test case performance: The optimization shows consistent 14-33% speedups across most test cases involving non-empty stacks, while maintaining identical performance for empty stack cases. This pattern is particularly beneficial for workloads where
peek()is frequently called on populated stacks, making it an effective micro-optimization for stack-heavy algorithms.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-Stack.peek-mha4o3cuand push.