⚡️ Speed up method BCDataStream.write_int32 by 27% #45
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.
📄 27% (0.27x) speedup for
BCDataStream.write_int32inelectrum/transaction.py⏱️ Runtime :
3.13 milliseconds→2.47 milliseconds(best of114runs)📝 Explanation and details
The optimization achieves a 26% speedup by inlining the
_write_nummethod directly intowrite_int32, eliminating the function call overhead and redundant operations.Key optimizations applied:
Function call elimination: The original code called
self._write_num('<i', val)which added function call overhead. The optimized version directly implements the struct packing and buffer operations inwrite_int32.Removed redundant assertion: The original
_write_numincluded anassert isinstance(s, (bytes, bytearray))check that's unnecessary sincestruct.pack()always returns bytes.Direct buffer manipulation: Both versions use the same efficient buffer operations (
bytearray(s)for initialization andinp.extend(s)for appending), but the optimized version accesses them directly without the indirection of a method call.Performance impact analysis:
write_int32spent 100% of its time just making the function call to_write_numWorkload benefits:
This optimization is particularly effective for:
The optimization preserves all original behavior and error handling while providing significant performance gains for this hot-path serialization method.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-BCDataStream.write_int32-mhmi39uoand push.