⚡️ Speed up function is_witness by 13%
#28
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.
📄 13% (0.13x) speedup for
is_witnessinelectrum/plugins/ledger/ledger.py⏱️ Runtime :
589 microseconds→521 microseconds(best of246runs)📝 Explanation and details
The optimized version achieves a 13% speedup by eliminating redundant operations through strategic variable caching:
Key optimizations:
Caches
len(script)once - The original code callslen(script)three times (lines with 27.4% and 21.1% of execution time). The optimized version stores it inscript_lenand reuses it, avoiding repeated length calculations.Caches
script[0]access - Instead of accessingscript[0]multiple times in conditional checks and the return statement, it's stored in thefirstvariable and reused.Why this improves performance:
len()calls on bytes objects require traversing the object header to read the length field each timescript[0]involves bounds checking and memory access that can be avoided through cachingTest case performance patterns:
The optimization is most effective for the common case of processing valid or nearly-valid witness scripts where multiple checks are performed.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
🔎 Concolic Coverage Tests and Runtime
codeflash_concolic_nuhjwnyo/tmphswaisuy/test_concolic_coverage.py::test_is_witnesscodeflash_concolic_nuhjwnyo/tmphswaisuy/test_concolic_coverage.py::test_is_witness_2codeflash_concolic_nuhjwnyo/tmphswaisuy/test_concolic_coverage.py::test_is_witness_3codeflash_concolic_nuhjwnyo/tmphswaisuy/test_concolic_coverage.py::test_is_witness_4codeflash_concolic_nuhjwnyo/tmphswaisuy/test_concolic_coverage.py::test_is_witness_5To edit these changes
git checkout codeflash/optimize-is_witness-mhfwx78tand push.